iOS – 在web视图中显示HTML资源文件或远程网页的内容

我是一个iOS新手。 我想要一个函数,根据常量中指定的内容从本地html资源文件或网页加载内容。 我怎么去做呢? 例如,如果我通过一个文件:// …到函数或http:// …,它应该相应的渲染。

你可以像这样轻松加载网页:

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

对于本地文件,它取决于设备上文件的位置:对于主包(=您的项目)中的文件,可以使用相同的loadRequest函数,但是build立不同的path:

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

如果你想在你的webView中加载一个htmlstring:

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

如果您的html文件驻留在您的应用程序的文档文件夹中(例如您下载的html文件):

 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] ;