helloB helloB - 1 year ago 102
iOS Question

Error: The file...doesn't exist when calling writeToFile on imageData

I am trying to write data to a file with the following code in a completion block for


void (^completionBlock)(NSURLResponse *response, NSURL *filePath, NSError *error) = ^void (NSURLResponse *response, NSURL *filePath, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (!error){
NSData *imageData = [NSData dataWithContentsOfURL:filePath];
if(imageData) NSLog(@"image is not null");

if(pic == 1) self.imageView.image = [UIImage imageWithData:imageData];
else if(pic==2) self.imageView2.image = [UIImage imageWithData:imageData];

NSArray *paths = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *documentsDirectoryURL = [paths lastObject];
NSURL *saveLocation;
if(pic == 1) saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:self.pictureName1];
else if (pic == 2) saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:self.pictureName2];
else saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:self.pictureName3];

NSLog(@"for # %d writing to file %@", pic, saveLocation);

NSError *error = nil;
[imageData writeToFile:[saveLocation absoluteString] options:NSAtomicWrite error: &error];
NSLog(@"FAILED\n\n\n %@ \n\n\n", [error description]);

I am able to display the downloaded images in
and my null check on
likewise confirms it's not null. However, when I try to write the data to a file, My
prints out the following error indicating that the write failed:

(log statements)
# 3 writing to file file:///var/mobile/Containers/Data/Application/3743A163-7EE1-4A5A-BF81-7D1344D6DA45/Documents/pic3.png
Error Domain=NSCocoaErrorDomain Code=4 "The file “pic1.jpg” doesn’t exist."
4A5A-BF81-7D1344D6DA45/Documents/pic1.jpg, NSUnderlyingError=0x16d67200 {Error
Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

I haven't been able to find another question on SO indicating this error message for this file, and I'm finding the error message quite counterintuitive. Where is my error?

Answer Source

Instead of [saveLocation absoluteString], use [saveLocation path]. Basically the former gives you "file:///path/filename" while the latter gives you "/path/filename", which is the correct format.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download