0

我正在做一个 iPhone 项目,我需要将相机图像保存到磁盘和文件,但下面的代码失败:(************

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

1 回答 1

3

您不应该有模拟器目录的硬编码路径。这将在设备上或模拟器重置时失败。您也不应该将用户数据保存在应用程序的 Document 文件夹之外的任何地方。

而是使用:

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

这将返回应用程序的 Document 目录的当前路径,无论它在哪里运行或发生了什么变化。

你不应该在 iPhone 代码中使用绝对路径,因为系统会打乱路径以确保安全。始终根据需要使用动态检索路径的函数。

于 2010-03-04T19:26:21.033 回答