Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone - NSData from local file's URL

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.

like image 819
lostInTransit Avatar asked Oct 03 '09 17:10

lostInTransit


People also ask

What is Nsurl?

An NSURL object is composed of two parts—a potentially nil base URL and a string that is resolved relative to the base URL. An NSURL object is considered absolute if its string part is fully resolved without a base; all other URLs are considered relative.

What is URL in Swift?

A value that identifies the location of a resource, such as an item on a remote server or the path to a local file. iOS 7.0+ iPadOS 7.0+ macOS 10.9+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+ Xcode 8.0+


1 Answers

// 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) 
like image 68
Tim Avatar answered Sep 22 '22 12:09

Tim