ios - 更新后保存的照片不会出现在设备上

标签 ios iphone ipad filepath

在我的 iPhone 应用程序中,我通过以下代码保存与事件关联的图片:

[pngData writeToFile:filePath atomically:YES]; //Write the file

self.thisTransaction.picPath = filePath;

稍后我使用以下代码检索并显示照片:

UIImage * image = [UIImage imageWithContentsOfFile:thisTransaction.picPath];

在我的 iPad 上运行良好(我没有 iPhone)。

但是,如果我在不涉及上述几行的 Xcode 代码修改后通过将 iPad 连接到我的 MB Pro 来更新应用程序,然后断开连接并独立运行它,则预期 picPath 处的图片为未检索到。 Core Data 中与 thisTransaction 关联的所有其他数据均完好无损,但更新后设备上没有出现预期的图片。

有人可以告诉我哪里出错了吗?

编辑以澄清文件路径构造

pngData = UIImagePNGRepresentation(capturedImage.scaledImage);

NSLog(@"1 The size of pngData should be %lu",(unsigned long)pngData.length);

//Save the image someplace, and add the path to this transaction's picPath attribute
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory



int timestamp = [[NSDate date] timeIntervalSince1970];

NSString *timeTag = [NSString stringWithFormat:@"%d",timestamp];

filePath = [documentsPath stringByAppendingPathComponent:timeTag]; //Add the file name


NSLog(@"1 The picture was saved at %@",filePath);

控制台日志显示此文件路径:

/Users/YoursTruly/Library/Developer/CoreSimulator/Devices/65FB33E1-03A7-430D-894D-0C1893E03120/data/Containers/Data/Application/EB9B9523-003E-4613-8C34-4E91B3357F5A/Documents/1433 624434

>

最佳答案

您遇到的问题是应用沙箱的位置会随着时间而改变。这通常发生在更新应用程序时。因此,您能做的最糟糕的事情就是保留绝对文件路径。

您需要做的只是保留相对于基本路径的路径部分(在本例中为“Documents”文件夹)。

然后,当您想要再次重新加载文件时,将保留的相对路径附加到“Doc​​uments”文件夹的当前值。

所以你的代码需要是这样的:

保存文件:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
int timestamp = [[NSDate date] timeIntervalSince1970];
NSString *timeTag = [NSString stringWithFormat:@"%d",timestamp];
filePath = [documentsPath stringByAppendingPathComponent:timeTag]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file

self.thisTransaction.picPath = timeTag; // not filePath

加载文件:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:thisTransaction.picPath];
UIImage *image = [UIImage imageWithContentsOfFile:filePath];

关于ios - 更新后保存的照片不会出现在设备上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30687270/

相关文章:

ios - 如何在 didDetermineState 方法中打开应用程序

ios - Nativescripts - 在 Web View 中单击按钮时打开浏览器

iphone - iOS:无法使用导航 Controller 显示 View

iphone - Swift 中的 Dropbox 集成

iphone - 在 UIButton 上使用两个不同的控制事件

ios - iPad App Store 链接不显示 iPhone 应用程序

iphone - 在 iOS 中检测 iTunes Store 的国家

ios - iOS 11 中的静默推送通知被忽略。

ios - (Int) -> $T4 与 NSMutableArray 不同

iphone - 带有纹理的 quartz 绘图