iPhone - NSData from local file's URL

lostInTransit picture lostInTransit · Oct 3, 2009 · Viewed 75.4k times · Source

I have a NSURL object which gives me the path of a local file (in documents folder). I want to populate an NSData object with the contents of this file. Tried using dataWithContentsOfURL: but this fails. I know the file exists because the iPhone SDK returns the path.

Can someone please tell me how I can get an NSData object from the URL of a local file?

Thanks.

Answer

Tim picture Tim · Oct 3, 2009
// Given some file path URL: NSURL *pathURL
// Note: [pathURL isFileURL] must return YES
NSString *path = [pathURL path];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];

Swift code:

let data = FileManager.default.contents(atPath: path)