iPhone - NSData from local file's URL

IphoneNsdataNsurl

Iphone Problem Overview


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.

Iphone Solutions


Solution 1 - Iphone

// 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)

Solution 2 - Iphone

To get this work you just need to do:

NSURL *imgPath = [[NSBundle mainBundle] URLForResource:@"search" withExtension:@"png"];
NSString*stringPath = [imgPath absoluteString]; //this is correct  

//you can again use it in NSURL eg if you have async loading images and your mechanism 
//uses only url like mine (but sometimes i need local files to load)
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:stringPath]];
UIImage *ready = [[[UIImage alloc] initWithData:data] autorelease];

Solution 3 - Iphone

Make sure your local URL starts with "file://" then you would just have to do this:

 NSData *fileData = [NSData dataWithContentsOfFile:fileURL.path];

Solution 4 - Iphone

For swift3 I found answer from following URL helpful

( I was getting following path , after capturing image using phonegap plugin

file:///var/mobile/Containers/Data/Application/B64B06DE-7976-45CF-9BE2-661F0F309A06/tmp/abcded.jpg )

https://stackoverflow.com/a/41043447/6383908

if let videoURL = URL(string: urlString), let videodata = try? Data(contentsOf: videoURL) { //Add code of Alamofire here }

Solution 5 - Iphone

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlostInTransitView Question on Stackoverflow
Solution 1 - IphoneTimView Answer on Stackoverflow
Solution 2 - IphoneMarcin MałyszView Answer on Stackoverflow
Solution 3 - IphoneahbouView Answer on Stackoverflow
Solution 4 - IphoneChirag PurohitView Answer on Stackoverflow
Solution 5 - IphoneAnton TropashkoView Answer on Stackoverflow