Read and write a String from text file

前端 未结 21 1425
别跟我提以往
别跟我提以往 2020-11-22 00:02

I need to read and write data to/from a text file, but I haven\'t been able to figure out how.

I found this sample code in the Swift\'s iBook, but I still don\'t kno

21条回答
  •  粉色の甜心
    2020-11-22 00:39

    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)!)
    

提交回复
热议问题