Why HTML images are not loading in UIWebView - html

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

Related

Cannot load the CSS with NodeJS

I am beginner to NodeJS and facing problem in loading the CSS. Here is my code.
I am just creating a server running in 9090 port and loading the default HTML file.
var server = http.createServer(function(request, response) {
var html = fs.readFileSync('./FirstApp/HtmlPages/index.html');
response.writeHead(200,{"Content-Type": "text/html"});
response.write(html);
response.end();
});
server.listen(9090);
On Loading http://localhost:9090/ i am able to see the index.html html page but not able to see the linked css feature.(If i just load my index.html in browser i am able to see css feature but not through the server)
This is my simple HTML.
<html>
<head>
<link type="text/css" rel="stylesheet" href="./css/styles.css">
</head>
<body>
<h2 class="heading"><em>Login Page</em></h2>
</body>
</html>
CSS file
.heading {
text-align: center;
}
I can see below warning in browser console
Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:9090/css/styles.css".
any help would be much appreciated
The problem is that you have a created a web server that only serves a single file, the index.html. It does not read any CSS file from the local file system, and it does not serve any CSS files.
You could analyze the incoming request and see if the path of the request‘s URL points to the CSS file. If it does, read the CSS file instead of the HTML file and return it with the response.
Here's a working, modified version of your code (assuming that styles.css is located in a subdirectory of the dir where your index.html is located):
var server = http.createServer(function(request, response) {
if (request.url.match(/^\/css\//)) {
var css = fs.readFileSync('./FirstApp/HtmlPages' + request.url);
response.writeHead(200,{"Content-Type": "text/css"});
response.write(css);
response.end();
return;
}
var html = fs.readFileSync('./FirstApp/HtmlPages/index.html');
response.writeHead(200,{"Content-Type": "text/html"});
response.write(html);
response.end();
});
server.listen(9090);
Please note: I would only do this for learning purposes, not for building an actual production web application. For that, I would use an existing HTTP server solution, for example Express.
I would suggest checking your file path is correct when linking to the css file. Try removing the . and have your path as /css/styles.css (but it comes down to ensuring that you have the correct path.
As a beginner, a common mistake might be that you forgot to save your css file after you made your edits.
Also, you should use the chrome developer tool (right click on page and inspect) to see if your css is already being applied to your html.
If you can show us the index.html code, that might help as well.

wkwebview - display image from documents directory into local html

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)
}

Embed image in HTML r markdown document that can be shared

I have an R markdown document which is created using a shiny app, saved as a HTML. I have inserted a logo in the top right hand corner of the output, which has been done using the following code:
<script>
$(document).ready(function() {
$head = $('#header');
$head.prepend('<img src=\"FILEPATH/logo.png\" style=\"float: right;padding-right:10px;height:125px;width:250px\"/>')
});
</script>
However, when I save the HTML output and share the output, of course the user cannot see the logo since the code is trying to find a file path which will not exist on their computer.
So, my question is - is there a way to include the logo in the output without the use of file paths? Ideally I don't want to upload the image to the web, and change the source to a web address.
You can encode an image file to a data URI with knitr::image_uri. If you want to add it in your document, you can add the html code produced by the following command in your header instead of your script:
htmltools::img(src = knitr::image_uri("FILEPATH/logo.png"),
alt = 'logo',
style = 'float: right;padding-right:10px;height:125px;width:250px')

WKWebView doesn't present the HTML string in Mac OSX

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.

ios-css and js not working linked in html file when opening in UIWebview from Documents directory

I have following structure of my www folder in Documents directory in ios
Documents
--www
--index.html
--js
--script.js
--css
--style.css
My index.html file references script and style files as below:
<link rel="stylesheet" href="css/style.css" />
<script type="text/javascript" src="js/script.js"></script>
Please note, the files and directory structure are created after app launch, from a remote-downloaded and extracted zip file. So this is not an issue caused by Xcode folder groups being confused with the app bundle's Documents subfolders.
It works fine when run in a browser but when loading index.html in UIWebview programmatically, script and style are not working. Meanwhile the index file itself loads perfectly.
When I give full path of script and css in index.html file it working fine for me.
Why relative path not working?
Thanks in advance.
Apparently the document base is not the same as the app's Documents directory when loading the HTML file programatically.
Check out the BASE element in HTML, it goes within the <head> element:
http://www.w3.org/wiki/HTML/Elements/base
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>This is an example for the <base> element</title>
<base href="http://www.example.com/news/index.html">
</head>
<body>
<p>Visit the archives.</p>
</body>
</html>
To fix that, you'll have supply a Document base url manually. You haven't posted the code how you're programmatically loading the index.html file, so I will assume you're using the following UIWebView method:
- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
So now try out this code, see if it solves your problem:
// Get the app Documents path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
// Add www/index.html to the basepath
NSString *fullFilepath = [basePath stringByAppendingPathComponent:#"www/index.html"];// This must be filled in with your code
// Load the file, assuming it exists
NSError *err;
NSString *html = [NSString stringWithContentsOfFile:fullFilepath encoding:NSUTF8StringEncoding error:&err];
// Load the html string into the web view with the base url
[self.webview loadHTMLString:html baseURL:[NSURL URLWithString:fullFilepath]];
If that doesn't work, try updating the code of the HTML file that you get from the .zip file. Something like:
// Get the app Documents path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
// Add www/index.html to the basepath
NSError *err;
NSString *fullFilepath = [basePath stringByAppendingPathComponent:#"www/index.html"];
// Load the file, assuming it exists
NSString *html = [NSString stringWithContentsOfFile:fullFilepath encoding:NSUTF8StringEncoding error:&err];
// Check to ensure base element doesn't already exist
if ([html rangeOfString:#"<base"].location == NSNotFound) {
// HTML doesn't contain a base url tag
// Replace head with head and base tag
NSString *headreplacement = [NSString stringWithFormat:#"<head><base href=\"%#\">", fullFilepath];
html = [html stringByReplacingOccurrencesOfString:#"<head>" withString:headreplacement];
[html writeToFile:fullFilepath atomically:YES encoding:NSUTF8StringEncoding error:&err];
}
// Now the file has a base url tag
May be your JS And CSS File are not compiled by xcode.
Open your project with xcode and GO to 'Targets' and check in the 'Compile Sources' section . If your js file is present in that folder, move it to the 'Copy Bundle Resource' and delete is from "Compile Sources" folders.
After that delete app from your device, then Go to the Build menu in xcode and clean all Targets and recompile.
Check to see if your HTML file including with your js file.
May be its your trouble for loading js.
try this ...
i hope this will solve you problem
I also faced the same problem , I solved it by doing the simple thing when adding the files to XCode I did a small change that is shown in the figure below: you have to add files by choosing create folder references for any folders option
In the figure below one is for adding HTML , click copy also if you are adding file outside from project . if files are already present then no need to copy it again .