iOS - display content from an html resource file or remote webpage in a webview

和自甴很熟 提交于 2019-12-02 19:20:16
notyce

You can easily load webpages like this:

NSURLRequest *request = [NSURLRequest requestWithURL:
   [NSURL URLWithString:@"http://stackoverflow.com"]] ;

[webView loadRequest:request] ;

For local files it depends on the location of the file on your device: For files in your main-bundle (= your project), you can use the same loadRequest function, but build the path differently:

NSString *localFilePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"] ;
NSURLRequest *localRequest = [NSURLRequest requestWithURL:
  [NSURL fileURLWithPath:localFilePath]] ;

[webView loadRequest:localRequest] ;

and if you want to load a html-string in your webView:

NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:bundlePath];

NSString *htmlString = [bundlePath pathForResource:@"index" ofType:@"html"] ;
[webView loadHTMLString:htmlString baseURL:baseURL];

and if your html-file resides in your documents folder of your application (for example a html-file you downloaded):

NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"index.html"];
NSURLRequest *documentsRequest = [NSURLRequest requestWithURL:
  [NSURL fileURLWithPath:path]] ;

[webView loadRequest:documentsRequest] ;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!