I have an app with downloaded images to be displayed in local html. I am still using Objective-C because this app is 4 years old.
When first launch the app, it will download the images and other dynamic content (which I check, it is in Documents/content/ directory).
I have this code to get the content location:
NSString *contentBasePath = [app.contentManager contentBasePath];
which I get:
/var/mobile/Containers/Data/Application/4AFD30E2-F4F7-405A-9FE9-1857EEC11CC7/Documents/content
Then I have a few html pages that will call the downloaded images dynamically:
<div class="box-round benefits-thumbnail" style="background-image:url('file://{{../contentBasePath}}/{{filename}}');"></div>
Which I check, {{../contentBasePath}} will get:
/var/mobile/Containers/Data/Application/4AFD30E2-F4F7-405A-9FE9-1857EEC11CC7/Documents/content
and {{filename}} will get
example.jpg
which is all correct.
All this works with uiwebview. However I need to use wkwebview, the image did not show up.
I tried:
<div class="box-round benefits-thumbnail" style="background-image:url('{{../contentBasePath}}/{{filename}}');"></div>
and it still not working.
I googled and read around and it seems like wkwebview do not allow absolute path. so I tried as per this suggest:
[_webConfig.preferences setValue:#YES forKey:#"allowFileAccessFromFileURLs"];
and still not working.
How can I resolve this?
Seems like this is a limitation of the WebKit. As a workaround, you can write the HTML contents into a file in the documents directory and load it using [webView loadFileURL:fileUrl allowingReadAccessToURL:dirUrl]
Link to docs: https://developer.apple.com/documentation/webkit/wkwebview/1414973-loadfileurl
The files must be in the document directory.
I implemented the following to retrieve a document:
let documentDirUrl = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let fileNameWithExtension = "IMG_0002.PNG"
let indexFileUrl = documentDirUrl.appendingPathComponent(fileNameWithExtension)
if FileManager.default.fileExists(atPath: indexFileUrl.path) {
webView.loadFileURL(indexFileUrl, allowingReadAccessTo: documentDirUrl)
}
Related
When I try to load url everything works fine. I also tried to load normal HTML and that worked fine too.
But this html I got from API is so weird and without tags. Is it possible to somehow present this in webView?
This is how my HTML looks like:
Code to load it :
var html: String
html = cards[Int(slider.value)-1].content
print(html)
webView.loadHTMLString(html, baseURL: nil)
The API is returning the data URL-encoded. So you have two options:
Preferred: Try fetching the data non URL-encoded. Maybe by passing the accept header "text/html", assuming the API might default to "text/plain". Check the API documentation and your request headers.
As a fallback: Use NSString.removingPercentEncoding.
In new xCode 9.0:
I tried simply to load a HTML string inside webView (WKWebView) but I got a blank screen!
The strange thing is the same code is works in my other computer!
Is this a bug?
Here is the code
let filePath = Bundle.main.path(forResource: "my HTML file name", ofType: "html")
let htmlStr = try! NSString.init(contentsOfFile: filePath!, encoding: String.Encoding.utf8.rawValue)
webView.loadHTMLString(htmlStr as String, baseURL: nil)
You have to allow 'Outgoing Connections (Client)' in the project's capabilities. Make sure these are added to the entitlements file as well.
I know, it does not make any sense if you don't make any outgoing connections and just pure HTML, but this made it work for me.
I am trying to load an HTML file on WebView. The HTML contains image URLs. When I try to run that image URL on Web Browser, it works. The image gets displayed. But the same image does not get loaded in WebView in my app.
I found this question on Apple Developer Forum, it is still unanswered. Any help would be appreciated. Thanks
I faced a similar issue a few months ago, and I fixed it by replacing UIWebView with WKWebView.
WKWebView is the official replacement of UIWebView, take a look at its documentation:
Starting in iOS 8.0 and OS X 10.10, use WKWebView to add web content
to your app. Do not use UIWebView or WebView.
Please try to fetch your images using WKWebView.
Step 1: import WebKit in your class
import WebKit
Step 2: Add WebKit delegate to your controller
class ViewController: UIViewController, WKUIDelegate
Step 3: create variable of WKWebView type
var webView: WKWebView!
Step 4: Configure WKWebView. Override loadView() function with following line of code
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
Step 5: In viewDidLoad() pass URLRequest to webView()
let url = "your URL"
let request = URLRequest(url: url!)
webView.load(request)
I have an HTML file that is imported in my Xcode project with an image inside. The image is also inside my project folder but when I try to load the HTML file in the UIWebView the image is never loaded.
This is my HTML file:
<!DOCTYPE html>
<html>
<body>
<img src="background.png"/>
</body>
</html>
And here is my Swift code to load the HTML file:
var htmlFile = NSBundle.mainBundle().pathForResource("Travel", ofType: "html")
var htmlString = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding)
weeb.loadHTMLString(htmlString!, baseURL: nil)
What is going wrong here? Thank you.
I had the same issue. Here is my solution
create one folder for example html and put all html file along with your images and other resource. and then drag drop that html folder to your xcode project. xcode will ask you for copy at that time choose option "Create folder reference" and then finish, Check below screen shot.
So your folder structure look like this.
your html file will be
<!DOCTYPE html>
<html>
<body>
<img src="back.png"/>
</body>
</html>
To load this html file your webview use the below code.
let bundlePath = NSBundle.mainBundle().bundlePath
let htmlFile = "\(bundlePath)/html/sample.html"
let fileURL = NSURL(fileURLWithPath: htmlFile)
webview.loadRequest(NSURLRequest(URL: fileURL))
I think you have the answer in the following post where the guy says
Using relative paths or file: paths to refer to images does not work
with UIWebView. Instead you have to load the HTML into the view with
the correct baseURL
Using HTML and Local Images Within UIWebView
I am an Objective C beginner and currently building an iOS app that extracts images from HTML pages just like Pinterest.
By searching through stack overflow, I found HTMLReader was recommended by many to parse HTML, so I installed it.
However, there is not so much of documents on the web that explain about how to use this library except for the sample code on the github page.
Could anyone advise me of how to extract image URLs from web pages using HTMLReader?
Below is what I tried.
Objective-C Code
NSString * htmlBody = [_webView stringByEvaluatingJavaScriptFromString:
#"document.body.innerHTML"];
HTMLDocument *document = [HTMLDocument documentWithString:htmlBody];
NSLog(#"%#", [document firstNodeMatchingSelector:#"img src"].textContent);
Sample web URL I tried to parse
http://www.lifehack.org/articles/lifestyle/100-life-hacks-that-make-life-easier.html
Expected Outcome on the console
http://cdn-media-1.lifehack.org/wp-content/files/2014/09/US_map_-_states-370x208.png
(since it is the first image that comes up when I search for "src img" on this site)
Actual Outcome I got
(Null)
You have to do
HTMLElement *element = [document firstNodeMatchingSelector:#"img"];
To get the image url, you just have to access the HTMLElement's attributes NSDictionary, and get the object for key "src":
NSString *urlString = element.attributes["src"];