Reputation: 105
Im using this method in order to store images and it is to my understanding that this method stores data persistently. The problem is that when I restart the simulator al the images are gone/unable to load. Anyway here's the code:
- (NSString *)saveImage:(NSMutableString*)account{
NSString *dir=[NSString stringWithFormat:@"http://example.com"];
NSURL *url=[NSURL URLWithString:dir];
NSData *imageData = UIImagePNGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfURL:url]]);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *imageName = [NSString stringWithFormat:@"%@%@", account,@"Banner.png"];
NSString *imagePath = [documentDirectory stringByAppendingFormat:imageName];
NSLog((@"pre writing to file"));
NSError *writeError = nil;
if(![imageData writeToFile:imagePath options:NSDataWritingAtomic error:&writeError]){
NSLog(@"%@: Error saving image: %@",[self class], [writeError localizedDescription]);
}
else{
NSLog(@"the cachedImagePath is %@", imagePath);
return imagePath;
}
return NULL;
}
This is the method used to load the image:
[UIImage imageWithContentsOfFile:bannerPath]
bannerPath is the imagePath returned from the saving method stored in NSUserDefaults.
Am I doing something wrong? How can I fix it? Thanks.
edit: I check with the following method if the file exists:
[[NSFileManager defaultManager] fileExistsAtPath:bannerPath];
I returns false.
Upvotes: 0
Views: 105
Reputation: 1103
NSString *imagePath = [documentDirectory stringByAppendingFormat:imageName];
i think should be
NSString *imagePath = [documentDirectory stringByAppendingPathComponent:imageName];
Upvotes: 1
Reputation: 446
This line
NSString *imageName = [NSString stringWithFormat:@"%@%@", account,@"Banner.png"];
is missing a /, it should be
NSString *imageName = [NSString stringWithFormat:@"/%@%@", account,@"Banner.png"];
You were writing an image name "DocumentsxxxxBanner.png" in directory
/Users/xxxx/Library/Developer/CoreSimulator/Devices/D523E2E5-0B28-4D0D-8187-67D50A628481/data/Containers/Data/Application/82F36569-C3C0-46D9-AF60-044F7B484724/
instead of an image named "xxxxBanner.png" in directory
/Users/xxxx/Library/Developer/CoreSimulator/Devices/D523E2E5-0B28-4D0D-8187-67D50A628481/data/Containers/Data/Application/82F36569-C3C0-46D9-AF60-044F7B484724/Documents
Cheers
Upvotes: 0