0

I want to in my app, be able to allow users to save large images(jpg) as well as data for each image(txt) and load the images/data. I'm having trouble figuring out where to save these images and text files. Userdefault wouldnt work because of the size of the image files and I don't want to save in the documents directory because then the user can access and potentially corrupt the data.

Where is a good place to save large data files for my app so I can load them later?

Lightsout
  • 3,454
  • 2
  • 36
  • 65

2 Answers2

0

You can save and retrieve your files in application directory folder. Also you can use iCloud to save your files.

Use below code if you want to save and retrieve files from Directory folder .

Xcode 8.3.2 Swift 3.x. Using NSKeyedArchiver and NSKeyedUnarchiver

Reading file from documents

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")
}

Write file to documents

NSKeyedArchiver.archiveRootObject(finalDataDict, toFile:(jsonFilePath?.absoluteString)!)
Prashant Gaikwad
  • 3,493
  • 1
  • 24
  • 26
0

If for some reason you don't want to use the documents directory, or you want those data in a separate folder, or you don't want to permanently save them, you can also create your own temporary directory

saving data as file in a new directory (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 {}
}

Alternative approach: use Apple's UIDocumentInteractionController or UIActivityViewController and let the user choose how to save his/her documents:

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

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

Gefilte Fish
  • 1,600
  • 1
  • 18
  • 17