我有一个包含网站的目录,我需要将其添加到我的项目中。我将使用 uiwebview
加载它。
我尝试了几种添加它的方法,但都没有成功。这是我最后尝试的方式:
将整个网站目录复制到我的项目目录(实际的物理文件夹)。 之后,将目录拖到我的 xcode 项目中,并勾选“为任何添加的文件夹创建文件夹引用” 然后我查看了“build phases -> copy bundle resources ->...”,我看到它在那里
加载我的网页时:
-(void)loadUrl
{
NSString *str = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"websiteDir"]; // THIS IS RETURNING NIL!
NSURL *url = [NSURL URLWithString:str];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
我做错了什么?
最佳答案
这是错误的:
你得到 str 作为路径但是然后调用 URLWithString... 但是 str 不是 URLString 而是一个路径
要么使用 url = [NSURL fileUrlWithPath:str]
或者使用方法- (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)extension subdirectory:(NSString *)subpath
样本
-(void)loadUrl {
NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html" subdirectory:@"websiteDir"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
关于ios - 无法使用 [[NSBundle mainBundle] pathForResource ofType inDirectory] 加载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24537849/