![](/img/trans.png)
[英]UIImage not being saved in Documents directory and killing the app
[英]UIImage saved to app documents directory does not persist between app sessions
我的應用程序旨在從用戶視頻制作縮略圖,並將其與本地存儲在應用程序文檔目錄中,以供以后在UICollectionView中使用。 但是,似乎圖像只是臨時保存,因為重新啟動應用程序后無法訪問它們。 我究竟做錯了什么?
我正在使用許多以前的SO帖子中的代碼,例如本篇文章: 在iOS設備上本地存儲圖像,因此我不確定自己引入了什么錯誤。
我正在保存從用戶錄制的視頻中提取的縮略圖,如下所示:
NSArray *paths2 = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *documentsDirectory = [paths2 lastObject];//[self documentsDirectoryURL];
NSString *prefixString = @"IdlingVideo";
NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString] ;
NSString *uniqueFileName = [NSString stringWithFormat:@"%@_%@.png", prefixString, guid];
NSURL *saveLocation = [documentsDirectory URLByAppendingPathComponent:uniqueFileName];
NSString *imagePath =saveLocation.path;
[UIImagePNGRepresentation(newImage) writeToURL:saveLocation atomically:YES];
NSURL *filePathCompressed = [[NSURL alloc] initFileURLWithPath: imagePath];
我也嘗試過這個:
NSArray *paths2 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths2 objectAtIndex:0];
在這兩種情況下,我運行應用程序時一切正常。 縮略圖似乎已保存並顯示在我的UICollectionView
。 我還在創建UICollectionViewCell
時記錄了文件是否存在的確認UICollectionViewCell
:
if ([fileManager fileExistsAtPath:self.complaint.thumbnailURL.path]){
NSLog(@"file exists at path %@", self.complaint.thumbnailURL.path);
}else{
NSLog(@"file DOES NOT EXIST at path %@", self.complaint.thumbnailURL.path);
}
根據需要,當用戶UICollectionView
后UICollectionView
查看UICollectionView
時,此輸出“文件存在”。 因此,所有功能在一個會話中都可以正常運行。 但是,當用戶重新啟動應用程序時,圖像會丟失。 重新啟動應用程序后,文件似乎丟失了。 UICollectionViewCell
沒有圖像,並且記錄器指示該文件不存在。
我究竟做錯了什么?
根據Apple的文檔 ,Documents目錄的內容將保留,直到應用程序將其明確刪除為止。
下面的代碼是我到目前為止一直在使用的代碼,用於獲取文檔目錄的路徑。 因此,似乎您正在正確訪問documents目錄。
+ (NSString *) applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
很可能在代碼中的某處顯式刪除文檔目錄的內容。
removeItemAtPath:
”在項目中執行全局搜索。 這是與NSFileManager
一起使用的方法,用於刪除指定路徑下的文件。 removeItemAtPath:
在項目中搜索文本,請在該行上添加一個斷點。 或者
appDidFinishLaunching
方法時,檢查document目錄中是否包含內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.