How to save an array as a json file in Swift?

前端 未结 6 1809
旧时难觅i
旧时难觅i 2020-12-04 11:33

I\'m new at swift and I\'m having trouble with this. so what i need to do is save this array as a json file in the document folder of the iphone.

var levels          


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 12:04

    Here is Isuru's answer in Swift 4.2. This works in a playground:

    let documentsDirectoryPathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    let documentsDirectoryPath = NSURL(string: documentsDirectoryPathString)!
    
    let jsonFilePath = documentsDirectoryPath.appendingPathComponent("test.json")
    let fileManager = FileManager.default
    var isDirectory: ObjCBool = false
    
    // creating a .json file in the Documents folder
    if !fileManager.fileExists(atPath: (jsonFilePath?.absoluteString)!, isDirectory: &isDirectory) {
        let created = fileManager.createFile(atPath: jsonFilePath!.absoluteString, contents: nil, attributes: nil)
        if created {
            print("File created ")
        } else {
            print("Couldn't create file for some reason")
        }
    } else {
        print("File already exists")
    }
    
    // creating an array of test data
    var numbers = [String]()
    for i in 0..<100 {
        numbers.append("Test\(i)")
    }
    
    // creating JSON out of the above array
    var jsonData: NSData!
    do {
        jsonData = try JSONSerialization.data(withJSONObject: numbers, options: JSONSerialization.WritingOptions()) as NSData
        let jsonString = String(data: jsonData as Data, encoding: String.Encoding.utf8)
        print(jsonString as Any)
    } catch let error as NSError {
        print("Array to JSON conversion failed: \(error.localizedDescription)")
    }
    
    // Write that JSON to the file created earlier
    //    let jsonFilePath = documentsDirectoryPath.appendingPathComponent("test.json")
    do {
        let file = try FileHandle(forWritingTo: jsonFilePath!)
        file.write(jsonData as Data)
        print("JSON data was written to teh file successfully!")
    } catch let error as NSError {
        print("Couldn't write to file: \(error.localizedDescription)")
    }
    

提交回复
热议问题