0
votes

In my app i store images in my documents folder and store their URI in the database.

Whenever i'm trying to load the image based on the URI stored in the db, i get "nil" back as a result.

The stored URI looks like this:

/Users/myname/Library/Application Support/iPhone Simulator/6.0/Applications/78325CF9-73B0-4D0D-B136-FD8FF8D837C1/Documents/WC_45FEAF25-AC0C-4E91-A5E2-AA48215F1E48-3147-000005C6C9E65B42.jpg

When i look into it from iTerm i see that the image is there, but in iTerm i have to cd into the directory like this:

/Users/myname/Library/Application\ Support/iPhone\ Simulator/6.0/Applications/78325CF9-73B0-4D0D-B136-FD8FF8D837C1/Documents/WC_45FEAF25-AC0C-4E91-A5E2-AA48215F1E48-3147-000005C6C9E65B42.jpg

notice the backslashes before whitespaces

I'm trying to get the image using this function:

-(UIImage *) getImageFromURL:(NSString *)fileURL {
    UIImage * result;

    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    result = [UIImage imageWithData:data];

    return result; //result is always nil
}

Is the problem related to the backslashes? Any help is very much appreciated!

Sincerely,

Zoli

1
Shouldn't you be using [NSURL fileURLWithPath:fileURL]? - jjv360
why? URLWithString is exactly the function to use - Zoltan Varadi
Because it looks like you're using a local file URL, but if it doesn't contain file:// in front of it, it needs to be converted using fileURLWithPath. - jjv360
can you provide a code explaining how you'd do it? - Zoltan Varadi
It's exactly the same as what you've got there, just replace URLWithString: with fileURLWithPath:... - jjv360

1 Answers

1
votes

The solution was to not store the uri in the database, only the image name. (But still store the image in the documents directory) Then with the following function the image can be retrieved:

- (UIImage*)loadImageWithName:(NSString*) name
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:
                      [NSString stringWithString: name] ];
    UIImage* image = [UIImage imageWithContentsOfFile:path];
    return image;
}