Mushroomcloud Mushroomcloud - 3 months ago 43
Swift Question

write data to file with persistent storage, swift

I used core data for storing user information, and I tried to write the measurement data (coming from built-in accelerometer) by using "writeToFile".

The core data functioned well with persistent storage of the user data; however, those measurement data file stored by "writeToFile" would just gradually disappear after a long period/newer files were written.

Should I use SQLite or any other database for storing the file of measurement data? Or is it possible to use core data to store files (it seems not achievable though)? I would like to keep both the user data and measurement data into a persistent storage. Thanks for suggestions!!

func writeToFile () {

let firstName = String(trial!.project!)
let secondName = String(trial!.record!)


let exportFilePath = NSTemporaryDirectory() + "\(firstName)_\(secondName).csv"
let exportFileURL = NSURL(fileURLWithPath: exportFilePath)!
NSFileManager.defaultManager().createFileAtPath(exportFilePath, contents: NSData(), attributes: nil)


Update:
Problem solved by using "NSFileManager.defaultManager().URLForDirectory". The final code looks like this:

I'm not really sure if you need to state "createDirectoryAtURL" or if the file can be created anyway.

let documentsURL = NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: NSURL(), create: true, error: nil)

NSFileManager.defaultManager().createDirectoryAtURL(documentsURL!, withIntermediateDirectories: true, attributes: nil, error: nil)

let fileURL = documentsURL!.URLByAppendingPathComponent("\(firstName).csv")

NSFileManager.defaultManager().createFileAtPath(fileURL.path!, contents: NSData(), attributes: nil)

let fileHandle = NSFileHandle(forWritingToURL: fileURL, error: nil)
if let fileHandle = fileHandle {
...
fileHandle.writeData(csvData!)
...

Answer

You're using NSTemporaryDirectory to store your files. The whole point of that directory is that the files are temporary, meaning that the operating system is free to delete them. You say they disappear after "a long period"; that's exactly the intended behavior with NSTemporaryDirectory.

If you need to keep the files around, you should use the urls(for:in:) method on NSFileManager to get the location of the documents directory (.documentDirectory).