Reputation: 21883
I'm writing an image to the simulators cache directory using
NSURL *cacheDir = [[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory
inDomains:NSUserDomainMask].lastObject;
NSURL *avatarFileURL = [cacheDir URLByAppendingPathComponent:@"test.png" isDirectory:NO];
NSData *imageData = UIImagePNGRepresentation(avatarImage);
[imageData writeToURL:avatarFileURL atomically:YES];
This works fine and I've verified the image by logging the avatarFile
url and loading it into a browser, which displays the cache image.
I then try and read the test image back and I'm getting different results if I use imageWithContentsOfFile:
and imageWithData:
as follows:
NSURL *cacheDir = [[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory
inDomains:NSUserDomainMask].lastObject;
NSURL *avatarFileURL = [cacheDir URLByAppendingPathComponent:@"test.png" isDirectory:NO];
// Returns a nil.
NSString *avatarFile = avatarFileUrl.absoluteString;
UIImage *image1 = [UIImage imageWithContentsOfFile:avatarFile];
// Returns the image.
NSData *imageData = [NSData dataWithContentsOfURL:avatarFileUrl];
UIImage *image2 = [UIImage imageWithData:imageData];
I'm at a loss to explain why imageWithContentsOfFile
fails and imageWithData
works when they are both addressing the same URL. I've verified the URL by logging it and urls are exactly the same.
Anyone know why imageWithContentsOfFile
is not working?
Upvotes: 0
Views: 173
Reputation: 318774
Your issue is with this line:
NSString *avatarFile = avatarFileUrl.absoluteString;
Look at the value of avatarFile
. It will be something like file:///....
. imageWithContentsOfFile:
expects a proper file path, not a file URL.
You need to properly convert the file URL into a path. That is done as follows:
NSString *avatarFile = avatarFileUrl.path;
Upvotes: 1