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

Saved photos don't appear on device after update

在我的 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/1433624434

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

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

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

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

保存文件:

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