Problem calling a Local HTML File from XCode

2019-02-19 09:12发布

问题:

Here's my WebView Code:

[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:
[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];

Here's my Error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', 
reason: '*** -[NSURL initFileURLWithPath:isDirectory:]: nil string parameter'

Can anyone help? It's saying nil string but the NSURL string is index.html

My only thought is that perhaps the index file isn't stored correctly. It's in the project directory - the same folder as the XCode project file xcodeproj and the info.plist

回答1:

Check that the file is copied to your application bundle. When [[NSBundle mainBundle] pathForResource:ofType:] returns nil very most likely there is no file with this name in the bundle

In Xcode3 right click the "Groups & Files" header in the side bar and select "target membership". Make sure the checkbox in front of index.html is checked.



回答2:

URLs have to define how to obtain information, not just what the file is called. This means you have to specify the full URL, like http://www.something.com/index.html or file:///Users/Daniel/Sites/index.html. What you are specifying is a URI not a URL

For the difference between a URL and URI: http://www.damnhandy.com/2007/11/19/uri-vs-url-whats-the-difference/

Apple docs for NSURL: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html