我是一名 iOS 新手。我想要一个函数,根据常量中指定的内容从本地 html 资源文件或网页加载内容。我该怎么做呢?例如,如果我将 file://... 传递给函数或 http://... ,它应该相应地呈现。
您可以轻松加载网页,如下所示:
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:@"http://stackoverflow.com"]] ;
[webView loadRequest:request] ;
对于本地文件,这取决于文件在您设备上的位置:
对于主包(=您的项目)中的文件,您可以使用相同的加载请求函数,但以不同的方式构建路径:
NSString *localFilePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"] ;
NSURLRequest *localRequest = [NSURLRequest requestWithURL:
[NSURL fileURLWithPath:localFilePath]] ;
[webView loadRequest:localRequest] ;
如果你想在 webView 中加载 html 字符串:
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] ;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)