Search code examples
iphonensstringnsurlnsbundle

Get image bytes


I am trying to load the bytes of an image like this:

NSURL *img = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"img" ofType:@"png"] isDirectory:NO];
NSString * test = [NSString stringWithContentsOfFile:[img absoluteString] encoding:NSASCIIStringEncoding error:&err];

But I always get following error:

Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn\u2019t be completed. 
(Cocoa error 260.)" UserInfo=0xc02abf0 
{NSFilePath=file://localhost/Users/admin/Library/Application%20Support/iPhone%20Simulator/4.3.2/Applications/C55551DB-152A-43D6-A1E0-9845105709D6/myApp.app/img.png,
 NSUnderlyingError=0xc02ccc0 "The operation couldn\u2019t be completed. Folder or file does not exist"}

However the file DOES exist, and if I copy/paste the NSFilePath into the browser it finds the image. What could be wrong?


Solution

  • Why not

    NSString *path = [[NSBundle mainBundle] pathforResource:@"img" ofType:"png"];
    
    NSData *data = [NSData dataWithContentsOfFile:path];
    

    You can't just store random bytes in an NSString - it will try to convert them into a string and might fail. You need to use an NSData object for binary data.

    You also don't need to use NSURLs at all; NSBundle will give you a path as a string.