Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import css file in UIWebView when I am using loadHTMLString() method in swift (iOS)

Tags:

css

ios

uiwebview

I have a common css file and some dynamic html text. What I am trying to do is load the css file from the disk and use dynamic html text to display in the UIWebView instead of putting the same css as text over and over again with the html text.

I am trying this way.

var sometext = "<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"></head>" + "<body><p>some text goes here</p></body></html>"
let mainbundle = NSBundle.mainBundle().bundlePath
let bundleURL = NSURL(fileURLWithPath: mainbundle)
self.webview.loadHTMLString(sometext, baseURL: bundleURL)

Now the problem is css is not getting applied to the html. Is there any one out there who can help, I think I am stuck.

Please help. Thanks!

like image 825
russell Avatar asked Jul 11 '15 03:07

russell


People also ask

How do I import HTML into WKWebView?

Load Local HTML File to a WKWebViewlet myUrl = myProjectBundle. url(forResource: "my-html-file", withExtension: "html")! where: my-html-file – is the name of HTML file you want to load into WKWebView from your App Bundle.

How do I display HTML data in swift Webview?

How to load a HTML string into a WKWebView or UIWebView: loadHTMLString() If you want to load resources from a particular place, such as JavaScript and CSS files, you can set the baseURL parameter to any URL .


1 Answers

I had the same problem. My code was almost exactly the same as what Russell posted.

Adding my css file to the project was not enough. I had to reference the file in the "Copy Bundle Resources" list in the Build Phase settings.

How to reference the file in XCode 7:

  1. Select the Build Phase tab
  2. Scroll down to the "Copy Bundle Resources" section and add your file. (note: if *.css files don't appear in the list. Click the "Add Other" button)
  3. In the options window choose "Create Folder Reference"

Thats it. This worked for me.

like image 143
Thu Trinh Avatar answered Oct 18 '22 01:10

Thu Trinh