簡體   English   中英

更新后,保存的照片不會顯示在設備上

[英]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的圖片。 核心數據中與此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);

控制台日志顯示以下文件路徑:

/用戶/ YoursTruly /庫/開發商/ CoreSimulator /設備/ 65FB33E1-03A7-430D-894D-0C1893E03120 /數據/容器/數據/應用/ EB9B9523-003E-4613-8C34-4E91B3357F5A /文檔/ 1433624434

您遇到的問題是應用程序沙箱的位置可能會隨時間變化。 通常,這是在更新應用程序時發生的。 因此,您最糟糕的事情是保留絕對文件路徑。

您需要做的是僅保留相對於基本路徑的路徑的一部分(在本例中為“ 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];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM