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

前端 未结 6 1818
旧时难觅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:16

    I recommend that you use SwiftyJSON framework. Study its documentation and in addition learn how to write strings to files (hint: NSFileHandle)

    Something like the code below, but you really need to study both SwiftyJSON and NSFileHandle to learn how to both serialize JSON data to a file and parse JSON data from a file

    let levels = ["unlocked", "locked", "locked"]
    let json = JSON(levels)
    let str = json.description
    let data = str.dataUsingEncoding(NSUTF8StringEncoding)!
    if let file = NSFileHandle(forWritingAtPath:path) {
        file.writeData(data)
    } 
    

提交回复
热议问题