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
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.