我正在制作一个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];
}
}
答案 0 :(得分:3)
您不应该有模拟器目录的硬编码路径。这将在设备上或模拟器重置时失败。除了应用程序的文档文件夹之外,您也不应该将用户数据保存在任何地方。
改为使用:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathToDocuments=[paths objectAtIndex:0];
这将返回应用程序的Document目录的当前路径,无论它在何处运行或已更改。
您永远不应在iPhone代码中使用绝对路径,因为系统会对安全路径进行扰乱。始终使用根据需要动态检索路径的函数。