How to call HTML file with css, js and images?

2019-09-20 18:26发布

I am downloading zip file from server. In NSCachesDirectory I have the html file and I would like to know how to run html file with their source files, I have pasted my code. please help me

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsPath =  [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"/Lesson-file/Lesson%d",[str_lsn_id integerValue]]];

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"story_html5" ofType:@"html" inDirectory:documentsPath]];
[lsn_play_webview loadRequest:[NSURLRequest requestWithURL:url]];

1条回答
相关推荐>>
2楼-- · 2019-09-20 18:59

This is an approach for you. From the context that you said that you have source files js and css.

Here issue may be because of on run time these files are not loaded or compiler not able to find their location.

For exmaple:

  <!--For CSS file html tag is-->
  <link rel="stylesheet" href="styles.css"> 

  <!--For JS file html tag is-->
  <script type="text/javascript" src="exmample.js"></script>

So you have to manually provide location of these files.

See the tags here href and src. These are location of resource files which will required on runtime when your html page is loaded in memory.

How ever if these files are in same directory than there is no need to provide url

Suggestion:

It is advisable that you provide file location url here. Edit your html file and add markers for the url tags.

Example code:

<html> <head>

        <script type="text/javascript" src="#JS-FILE1#"></script>
        <link rel="stylesheet" href="#CSS-FILE1#">

</head> <body> </body>
</html>

You can see that I have replaced files with markers #JS-FILE1# and #CSS-FILE1#. Now we will replace these markers with actual urls before loading html file.

NSString *path = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"html"];
NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

// Location of Resource files
NSString *jsFilePath = [[NSBundle mainBundle] pathForResource:@"exmample" ofType:@"js"];

NSString *cssFilePath = [[NSBundle mainBundle] pathForResource:@"stylesheet" ofType:@"css"];

html = [html stringByReplacingOccurrencesOfString:@"#JS-FILE1#" withString:jsFilePath];
html = [html stringByReplacingOccurrencesOfString:@"#CSS-FILE1#" withString:cssFilePath];

Put here break point and debug the output string. NSLog this string copy it and create temporary file - open it in browser to cross check that all resources are loaded or not?

If not then check that url for resource files are correct.

查看更多
登录 后发表回答