views:

815

answers:

2

I am working on an iPhone project in which I need save camera images to disk and file but the code below fails: (****

-(void)imagePickerController:(UIImagePickerController *) picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

[picker dismissModalViewControllerAnimated:YES];
imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
imgglobal =imageView.image;
NSString *newFilePath = [NSHomeDirectory() stringByAppendingPathComponent: @"~/Users/abc/Library/Application Support/iPhone Simulator/User/Applications/SAVE_IMAGE_TEST1.JPG"]; 
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 1.0);
NSData  *data = imageData;
if (imageData != nil) {
    [imageData writeToFile:newFilePath atomically:YES];
}
if ([[NSFileManager defaultManager] createFileAtPath:@"~/Users/abc/Library/Application Support/iPhone Simulator/User/Applications/SAVE_IMAGE_TEST1.JPG" contents:data attributes:nil])
{
    UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Image was successfully saved to the Photo Library." delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
    [successAlert show];
    [successAlert release];
} else {
    UIAlertView     *failureAlert = [[UIAlertView alloc] initWithTitle:@"Failure" message:@"Failed to save image to the Photo Library." delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
    [failureAlert show];
    [failureAlert release];
}       
}
+2  A: 

You shouldn't have a hard coded path to the simulator directories. That will fail on the device or when the simulator resets. Neither should you save user data anywhere but the app's Document folder.

Instead use:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathToDocuments=[paths objectAtIndex:0];

This will return the current path the app's Document directory regardless of where it is run or what has changed.

You should never use absolute paths in iPhone code because the system scrambles the paths for security. Always use the functions that dynamically retrieve the paths as needed.

TechZen
A: 

follow what TechZen says, but also turn this:

    if (imageData != nil) {
    [imageData writeToFile:newFilePath atomically:YES];
}
if ([[NSFileManager defaultManager] createFileAtPath:@"~/Users/abc/Library/Application Support/iPhone Simulator/User/Applications/SAVE_IMAGE_TEST1.JPG" contents:data attributes:nil]) {
...
} else {
...
}

into this:

if (imageData != nil) {
if ([imageData writeToFile:newFilePath atomically:YES]) {
...
} else {
...
}
}

NSFileManager's createFile is the same as NSData's writeToFile, but the NSData method is more commonplace

ckrames1234