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

前端 未结 6 1824
旧时难觅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 11:55

    In Swift 4 this is already built-in with JSONEncoder.

    let pathDirectory = getDocumentsDirectory()
    try? FileManager().createDirectory(at: pathDirectory, withIntermediateDirectories: true)
    let filePath = pathDirectory.appendingPathComponent("levels.json")
    
    let levels = ["unlocked", "locked", "locked"]
    let json = try? JSONEncoder().encode(levels)
    
    do {
         try json!.write(to: filePath)
    } catch {
        print("Failed to write JSON data: \(error.localizedDescription)")
    }
    
    func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }
    

    The object you're trying to encode must conform to the Encodable protocol.

    Read Apple's official guide on how to extend existing objects to be encodable.

提交回复
热议问题