iPhone: How to Write an Image to Disk in the App Directories
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] createFil开发者_如何转开发eAtPath:@"~/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];
}
}
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.
精彩评论