4

i am trying to load .js and .css files from within app resources to uiwebview. and i am able to load .js file but can not load .css file please help. here is my code

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //NSString *cssFile = @"styling.css";

    NSString *jsFile = @"storage.js";
    NSString *jsFilePath = [[NSBundle mainBundle] pathForResource:jsFile ofType:nil];
    NSURL *jsURL = [NSURL fileURLWithPath:jsFilePath];
    NSString *javascriptCode = [NSString stringWithContentsOfFile:jsURL.path encoding:NSUTF8StringEncoding error:nil];
    [webView stringByEvaluatingJavaScriptFromString:javascriptCode];
}

this code it working perfectly for .js file but how can i use .css file in it?

Vix Hunk
  • 303
  • 4
  • 17
  • Well... Add an error and tell us, what it says! `NSError *e; [NSString stringWithContentsOfFile:jsURL.path encoding:NSUTF8StringEncoding error:&e]; if (e) { NSLog(@"%@", e); }` – Julian F. Weinert Apr 19 '18 at 12:49
  • there is no error for now with js file it is working perfectly but i need to know how can i include css file. – Vix Hunk Apr 19 '18 at 13:06
  • @VixHunk Did you check this post https://stackoverflow.com/questions/33123093/insert-css-into-loaded-html-in-uiwebview-wkwebview? – trungduc Apr 19 '18 at 14:49
  • You could try this solution [https://stackoverflow.com/questions/33123093/insert-css-into-loaded-html-in-uiwebview-wkwebview](https://stackoverflow.com/questions/33123093/insert-css-into-loaded-html-in-uiwebview-wkwebview) – Solomiya Apr 19 '18 at 15:02
  • @Solomiya tried this one but not working. my .php file is remotely loading in webview. and js n css files in bundle. – Vix Hunk Apr 20 '18 at 10:28
  • @VixHunk what do you try to say? There is no error? Please show us the code you are using to load your CSS file if it isn't the same – Julian F. Weinert Apr 21 '18 at 23:00
  • @JulianF.Weinert please read my question again. i tried the code that link you provided but it is'nt working not even giving any error. i need to know how to add .css file for remote url php page from scratch. i already did for .js file and its working. but i will i do it for css file. – Vix Hunk Apr 23 '18 at 08:43

4 Answers4

2
NSString *HTML_HEADER=@"<HTML><HEAD><link rel='stylesheet' href='#FILE1#' type='text/css'></HEAD><BODY>";
NSString *HTML_FOOTER=@"</BODY></HTML>";

NSString *cssFilePath = [[NSBundle mainBundle] pathForResource:@"style" ofType:@"css"];
NSString *html_header_with_files = [HTML_HEADER stringByReplacingOccurrencesOfString:@"#FILE1#" withString:cssFilePath];

NSString *htmlString = [NSString stringWithFormat:@"%@%@%@",html_header_with_files,yourHtmlFile.html,HTML_FOOTER];

NSLog(@"htmlString %@", htmlString);
// Load HTML
[self.webView loadHTMLString:htmlString baseURL:nil];

Note: Add your all CSS/JS/HTML files to Project Properties >> Build Phases >> Copy Bundle Resources.

Ganpat
  • 768
  • 3
  • 15
  • 30
  • my html is not in bundle it will load remotely from a url – Vix Hunk Apr 20 '18 at 10:26
  • Simply load your html content from URL to string variable. And replace the below line in above code. `NSString *htmlString = [NSString stringWithFormat:@"%@%@%@",html_header_with_files,yourHtmlContent,HTML_FOOTER];` – Ganpat Apr 21 '18 at 05:25
  • what is yourHtmlContent? – Vix Hunk Apr 23 '18 at 08:47
  • and please also tell me where should i put this code? – Vix Hunk Apr 23 '18 at 08:47
  • `yourHtmlContent` is complete HTML source code in `NSString` variable. You can put the above code in `ViewDidLoad`. Last line of code will load your HTML content in webView. – Ganpat Apr 24 '18 at 04:17
  • my html code is remote its a website/url that i am loading in ViewDidLoad – Vix Hunk Apr 24 '18 at 08:00
  • Then you needs to get HTML content in string variable. `NSString *url = @"http://www.example.com"; NSURL *urlRequest = [NSURL URLWithString:url]; NSError *err = nil; NSString * yourHtmlContent = [NSString stringWithContentsOfURL:urlRequest encoding:NSUTF8StringEncoding error:&err]; if(err) { //Handle }` – Ganpat Apr 24 '18 at 08:55
2

You are basically on the right track, but you should be able to add the css using the same stringByEvaluatingJavaScriptString method.

- (void)webViewDidFinishLoad:(UIWebView *)webView {


    NSString *jsFile = @"storage.js";
    NSString *jsFilePath = [[NSBundle mainBundle] pathForResource:jsFile ofType:nil];
    NSURL *jsURL = [NSURL fileURLWithPath:jsFilePath];
    NSString *javascriptCode = [NSString stringWithContentsOfFile:jsURL.path encoding:NSUTF8StringEncoding error:nil];
    [webView stringByEvaluatingJavaScriptFromString:javascriptCode];

    // Updated to load css from "styling.css" file. 
    NSString *cssFile = @"styling.css";
    NSString *cssFilePath = [[NSBundle mainBundle] pathForResource:jsFile ofType:nil];
    NSURL *cssURL = [NSURL fileURLWithPath:jsFilePath];
    NSString *cssString = [NSString stringWithContentsOfFile:jsURL.path encoding:NSUTF8StringEncoding error:nil];

    // NSString *cssString = @"body { font-family: Verdana, Geneva, sans-serif; font-size: 50px; color: #F00; }";

    NSString *javascriptString = @"var style = document.createElement('style'); style.innerHTML = '%@'; document.head.appendChild(style)"; 
    NSString *javascriptWithCSSString = [NSString stringWithFormat:javascriptString, cssString];
    [webView stringByEvaluatingJavaScriptFromString:javascriptWithCSSString]; 

}

Once you do this, you can verify that the style is applied by using Safari remote debugging to view the source for the page displayed on the device / simulator. It can show you if some existing CSS is overriding yours.

wottle
  • 13,095
  • 4
  • 27
  • 68
  • your code worked perfectly but yeah you are right. but how can i do this "cssString" with my styling.css. how can i pass that file coding inside this cssString – Vix Hunk Apr 26 '18 at 08:07
  • I updated the response to load the css from a file named styling.css. If it no longer works, either the file is not included in your target, the file name is not right, or there are errors in the css that are causing it not to be valid (most likely). – wottle Apr 26 '18 at 12:12
0

I have written on how to add .css file in Xcode and load any HTML String along with applying the local css, in a wkwebview

https://medium.com/if-let-swift-programming/css-in-your-xcode-project-2b7011a29cb3

Do check if any of this helps.

Creating a .css file

⏩ Open Text Edit (Ensure you have ‘Make Plain Text’ selected under Format, or you might keep wondering how to save with .css extension)

⏩ Scribble down your css code that you would want to apply on your web view’s HTML string (In my case I wanted 2 types of fonts, some custom properties on links and an image instead of a bullet item, so below is what my css file looks like)

@font-face
{
 font-family: 'Gotham-Book';
 src: local('Gotham-Book'),url('Gotham-Book.otf') format('opentype');
}
@font-face
{
 font-family: 'Gotham-Medium';
 src: local('Gotham-Medium'),url('Gotham-Medium.otf')    format('opentype');
}
a {
 color: #16A4FA;
 text-decoration: none;
}
li {
 margin: 0 0 0 -30px;
 padding: 10px 0 10px 40px;
 list-style: none;
 background-image: url('myImage.png');
 background-repeat: no-repeat;
 background-position: left top 8px;
 background-size: 30px;
}

Here, Note that if you want some images to be loaded in your web view you will have to add them as a resource file in your project (It won’t load from your Assets.xcassets)

Add .css in xcworkspace It’s as easy as adding some resource file

⏩ Add your file by dragging it to your desired location, and copy items if needed

⏩ Ensure your file is present in the Build Phases > Copy Bundle Resources list

Loading HTML string in your web view

import WebKit

extension WKWebView {

    func loadHTML(fromString: String, colorHEX: String = "#757575", fontFamily: String = "Gotham-Book", fontSize: String = "14") {
        let htmlString = """
        <link rel="stylesheet" type="text/css" href="myCSSFile.css">
        <span style="font-family: '\(fontFamily)'; font-weight: normal; font-size: \(fontSize); color: \(colorHEX)">\(fromString)</span>
        """
        self.loadHTMLString(htmlString, baseURL: Bundle.main.bundleURL)
    }
}

Calling

/// webView is a WKWebView.
webView.loadHTML(fromString: "yourHTMLStringGoesHere")
Mansi
  • 628
  • 1
  • 8
  • 18
0
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    // Load file .js
    NSString *jsFile = @"storage.js";
    NSString *jsFilePath = [[NSBundle mainBundle] pathForResource:jsFile ofType:nil];
    NSURL *jsURL = [NSURL fileURLWithPath:jsFilePath];
    NSString *javascriptCode = [NSString stringWithContentsOfFile:jsURL.path encoding:NSUTF8StringEncoding error:nil];
    [webView stringByEvaluatingJavaScriptFromString:javascriptCode];
    // Load file .css
    NSString *cssFile = @"styling.css";
    NSString *cssFilePath = [[NSBundle mainBundle] pathForResource:cssFile ofType:nil];
    NSURL *cssURL = [NSURL fileURLWithPath:cssFilePath];
    NSString *cssCode = [NSString stringWithContentsOfFile:cssURL.path encoding:NSUTF8StringEncoding error:nil];
    NSString *jsAddCssString = @"var style = document.createElement('style'); style.innerHTML = '%@'; document.head.appendChild(style)";
    NSString *jsWithCssString = [NSString stringWithFormat:jsAddCssString, cssCode];
    [webView stringByEvaluatingJavaScriptFromString:jsWithCssString];
}

You can try it.

chaunv
  • 833
  • 6
  • 15
  • with this code it is getting .js but not css file please also review my .css file " body { font-family: Verdana, Geneva, sans-serif; font-size: 50px; color: #F00; }" – Vix Hunk Apr 25 '18 at 07:00
  • your file css is OK. You try to comment source code "Load file .js", only run source code "Load file .css", and see file .css is load OK or NOT? Please tell me result after run ? – chaunv Apr 26 '18 at 01:54
  • Oh, you try to assign direct code css into NSString variable: NSString * cssCode = @"body { font-family: Verdana, Geneva, sans-serif; font-size: 50px; color: #F00}";. Run app again and see result. (better still comment code load file js). – chaunv Apr 26 '18 at 08:49