2017-10-10 66 views
-1

我想在我的應用程序中,允許用戶保存大圖像(jpg)以及每個圖像(txt)的數據並加載圖像/數據。我無法確定保存這些圖像和文本文件的位置。由於圖像文件的大小,Userdefault不起作用,我不想保存在文檔目錄中,因爲用戶可以訪問並可能損壞數據。在IOS中保存和加載大文件的位置

哪裏是我的應用程序保存大型數據文件的好地方,以便以後可以加載它們?

+0

用於存儲圖像使用的核心數據。 –

+0

我不希望用戶訪問保存的數據,所以我不能把「應用程序支持iTunes文件共享」放在我的info.plist中? – bakalolo

+0

@bakalolo你最終解決了你的問題嗎? –

回答

0

您可以在應用程序目錄文件夾中保存和檢索您的文件。你也可以使用iCloud來保存你的文件。

如果您想要從目錄文件夾中保存和檢索文件,請使用下面的代碼。

Xcode 8.3.2 Swift 3.x。使用從文件的NSKeyedArchiver和NSKeyedUnarchiver

閱讀文件

let documentsDirectoryPathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! 
let documentsDirectoryPath = NSURL(string: documentsDirectoryPathString)! 
let jsonFilePath = documentsDirectoryPath.appendingPathComponent("Filename.json") 

let fileManager = FileManager.default 
var isDirectory: ObjCBool = false 

if fileManager.fileExists(atPath: (jsonFilePath?.absoluteString)!, isDirectory: &isDirectory) { 

let finalDataDict = NSKeyedUnarchiver.unarchiveObject(withFile: (jsonFilePath?.absoluteString)!) as! [String: Any] 
} 
else{ 
    print("File does not exists") 
} 

文件寫入文件

NSKeyedArchiver.archiveRootObject(finalDataDict, toFile:(jsonFilePath?.absoluteString)!) 
0

如果由於某種原因你不想使用該文件的目錄,或您希望將這些數據放在單獨的文件夾中,或者您不想永久保存它們,也可以創建自己的臨時目錄

數據保存爲文件在新目錄中(SWIFT 3)

func saveToMyDirectory(data: Data, filename: String) { 
    var tempDirectoryURL = NSURL.fileURL(withPath: NSTemporaryDirectory(), isDirectory: true) 
    tempDirectoryURL = tempDirectoryURL.appendingPathComponent(filename) 
    do { 
     try data?.write(to: tempDirectoryURL) 
    } catch {} 
} 

替代做法:使用蘋果的UIDocumentInteractionController或UIActivityViewController並讓用戶選擇如何保存他/她的文件:

https://developer.apple.com/documentation/uikit/uidocumentinteractioncontroller

https://developer.apple.com/documentation/uikit/uiactivityviewcontroller