iPhone: How to Write an Image to Disk in the App Directories

喜你入骨 提交于 2019-12-08 13:18:44

问题


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];
}       
}

回答1:


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.



来源:https://stackoverflow.com/questions/2380173/iphone-how-to-write-an-image-to-disk-in-the-app-directories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!