Accessing Local file using NSURL

Trying to load anything from the filesystem root is wrong, wrong, wrong. Definitely wrong on the device, and probably wrong on the simulator. The resources directory should be accessed via the NSBundle class.

For example, to get a URL for a file called "Data.txt" in the resources, use the following:

NSURL *MyURL = [[NSBundle mainBundle]
    URLForResource: @"Data" withExtension:@"txt"];

If you want to get a URL from a path (say, because you created a file in NSTemporaryDirectory() and you need to get that as a URL) you can easily do so by using NSURL's fileURLWithPath method:

NSString* tempPath = NSTemporaryDirectory();
NSString* tempFile = [tempPath stringByAppendingPathComponent:fileName];
NSURL* URL = [NSURL fileURLWithPath:tempFile];

Much easier than +URLWithString: and other methods.

Tags:

Ios

Iphone