3. Save data to files

Original link:current page


If you need to save data to local files in swift, it's very easy.

First, create a swift file, for example, named “DataLog.swift”

In the class just be created:
Declare a file name, to specify where data will be save.

  var file = "DataLog.txt"
private func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let directoryPath = paths[0].appendingPathComponent(Constants.logPath, isDirectory: true)
 
    var isDirectory = ObjCBool(false)
    if !FileManager.default.fileExists(atPath: directoryPath.path, isDirectory: &isDirectory) {
        do {
            try FileManager.default.createDirectory(at: directoryPath, withIntermediateDirectories: false, attributes: nil)
        } catch {
            print("create directory failed")
        }
    }
    return directoryPath
}

This function return a url which like the format “<application field>/Documents/(Constants.logPath)“, the Constants.logPath is the directory where to store files, for example, “log”.
If the directory is not exist, then create it.


private func writeToFileEnd(file:String, str:String) {
    let url = getDocumentsDirectory().appendingPathComponent(file)
    if let fileHandle = try? FileHandle(forUpdating: url) {
        fileHandle.seekToEndOfFile()
        fileHandle.write(str.data(using: String.Encoding.utf8)!)
        fileHandle.closeFile()
    } else {
        do {
            try str.write(to: url, atomically: true, encoding: String.Encoding.utf8)
        } catch {
            print("write error")
        }
    }
}

This function write data str to file file, if file is not empty, append data to the end of file.


Also, you may need to clear file's data sometimes.

private func clearFile(file:String) {
    let url = getDocumentsDirectory().appendingPathComponent(file)
    do {
        try "".write(to: url, atomically: true, encoding: String.Encoding.utf8)
    } catch {
        print("write error")
    }
}

Clear the file file's data


After calling writeToFileEnd, you can get the file in iTunes → <your device> → File Sharing → <your app> → log (if Constants.logPath==“log”).

  • Last modified: 2019/08/23 12:18