Reading an image from a local folder in Objective-C

I need to read an image from a specific url.

It works great with WWW. but it returns null when the url specifies the local folder.

// Works NSString *sampleData = @"http://blogs-images.forbes.com/ericsavitz/files/2011/05/apple-logo2.jpg"; // Returns nil NSString *sampleData = @"USER/user2/..."; 

Note: I change NSString to NSURL and create a UIImage.

 NSURL *url = [NSURL URLWithString: data]; UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 
+4
source share
5 answers

You are sending the relative path for the file url. This relative path name is interpreted relative to the current working directory of the running application, which is not guaranteed to be anything special, and therefore is almost certainly not what you want.

You can either specify an absolute path - the one that starts with '/' - or set the current working directory of the application to something explicit, for example, in the folder of your user documents.

+1
source

you should probably take a look at the NSBundle class. Methods like

- (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)extension subdirectory:(NSString *)subpath

or

- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension

probably what you want

+1
source

First of all, you can NOT read the file from the path that you specified: "USER / user2 / ...", the file must be in your application or in the application sandbox.

Secondly, check the path string if some texts need to be encoded in the url. Try:

NSURL *url = [NSURL URLWithString:[data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

Also, if the URL is non-zero, you should also check if your [NSData dataWithContentsOfURL:url]; returns [NSData dataWithContentsOfURL:url]; zero. If so, it means your URL is incorrect, so the method cannot find your file.

PS, you are mistaken in creating the image code, you should call alloc before imageWithData:

0
source

You need to do something like a local URL:

 NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *pngFilePath = [NSString stringWithFormat:@"%@/%@", docDir, nameOfFile]; 

and finally upload the image:

 UIImage *image = [UIImage imageWithContentsOfFile:pngFilePath]; 
0
source

Try instead

 NSString *path = @"USER/user2/.../xxx.xxx"; NSFileManager *fileManager = [NSFileManager defaultManager]; BOOL isFileExist = [fileManager fileExistsAtPath:path]; UIImage *image; if (isFileExist) { image = [[UIImage alloc] initWithContentsOfFile:path]; } else { // do something.<br> } 
0
source

Source: https://habr.com/ru/post/1369437/


All Articles