【问题标题】:iPhone: How to Write an Image to Disk in the App DirectoriesiPhone:如何在应用程序目录中将图像写入磁盘
【发布时间】:2010-03-04 14:52:54
【问题描述】:

我正在做一个 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];
}       
}

【问题讨论】:

  • 你真的应该在你的计算机上而不是在 iPhone 环境中指定一个位置的路径吗?

标签: iphone uiimagepickercontroller nsdata nsfilemanager


【解决方案1】:

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

改为使用:

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

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

您不应该在 iPhone 代码中使用绝对路径,因为系统会为了安全起见对路径进行打乱。始终根据需要使用动态检索路径的函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 2019-07-16
    • 2017-03-19
    相关资源
    最近更新 更多