iOS - 显示来自webview中的html资源文件或远程网页的内容 [英] iOS - display content from an html resource file or remote webpage in a webview
问题描述
我是iOS新手。我希望有一个函数从本地html资源文件或网页加载内容,具体取决于常量中指定的内容。我该怎么做呢?例如,如果我将文件:// ...传递给函数或http:// ...,则应相应地进行渲染。
I am an iOS newbie. I want to have a function that loads the content from a local html resource file or a webpage depending on what is specified in a constant. How would I go about doing it? For eg, if I pass a file://... to the function or an http://... , it should render accordingly.
推荐答案
您可以轻松加载如下网页:
You can easily load webpages like this:
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:@"http://stackoverflow.com"]] ;
[webView loadRequest:request] ;
对于本地文件,它取决于设备上文件的位置:
对于文件在你的主包(=你的项目)中,你可以使用相同的 loadRequest 函数,但以不同方式构建路径:
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] ;
如果你想在webView中加载一个html字符串:
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];
如果您的html文件位于应用程序的文档文件夹中(例如html文件)你下载了):
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] ;
这篇关于iOS - 显示来自webview中的html资源文件或远程网页的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!