#1. Save a Swift Array
as a json file
The following Swift 3 / iOS 10 code shows how to transform an Array
instance into json data and save it into a json file located in an iPhone's document directory using FileManager
and JSONSerialization
:
func saveToJsonFile() {
// Get the url of Persons.json in document directory
guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileUrl = documentDirectoryUrl.appendingPathComponent("Persons.json")
let personArray = [["person": ["name": "Dani", "age": "24"]], ["person": ["name": "ray", "age": "70"]]]
// Transform array into data and save it into file
do {
let data = try JSONSerialization.data(withJSONObject: personArray, options: [])
try data.write(to: fileUrl, options: [])
} catch {
print(error)
}
}
/*
Content of Persons.json file after operation:
[{"person":{"name":"Dani","age":"24"}},{"person":{"name":"ray","age":"70"}}]
*/
As an alternative, you can implement the following code that use streams:
func saveToJsonFile() {
// Get the url of Persons.json in document directory
guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileUrl = documentDirectoryUrl.appendingPathComponent("Persons.json")
let personArray = [["person": ["name": "Dani", "age": "24"]], ["person": ["name": "ray", "age": "70"]]]
// Create a write-only stream
guard let stream = OutputStream(toFileAtPath: fileUrl.path, append: false) else { return }
stream.open()
defer {
stream.close()
}
// Transform array into data and save it into file
var error: NSError?
JSONSerialization.writeJSONObject(personArray, to: stream, options: [], error: &error)
// Handle error
if let error = error {
print(error)
}
}
/*
Content of Persons.json file after operation:
[{"person":{"name":"Dani","age":"24"}},{"person":{"name":"ray","age":"70"}}]
*/
#2. Get a Swift Array
from a json file
The following Swift 3 / iOS 10 code shows how to get data from a json file located in an iPhone's document directory and transform it into an Array
instance using FileManager
and JSONSerialization
:
/*
Content of Persons.json file:
[{"person":{"name":"Dani","age":"24"}},{"person":{"name":"ray","age":"70"}}]
*/
func retrieveFromJsonFile() {
// Get the url of Persons.json in document directory
guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileUrl = documentsDirectoryUrl.appendingPathComponent("Persons.json")
// Read data from .json file and transform data into an array
do {
let data = try Data(contentsOf: fileUrl, options: [])
guard let personArray = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: [String: String]]] else { return }
print(personArray) // prints [["person": ["name": "Dani", "age": "24"]], ["person": ["name": "ray", "age": "70"]]]
} catch {
print(error)
}
}
As an alternative, you can implement the following code that use streams:
/*
Content of Persons.json file:
[{"person":{"name":"Dani","age":"24"}},{"person":{"name":"ray","age":"70"}}]
*/
func retrieveFromJsonFile() {
// Get the url of Persons.json in document directory
guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileUrl = documentsDirectoryUrl.appendingPathComponent("Persons.json")
// Create a read-only stream
guard let stream = InputStream(url: fileUrl) else { return }
stream.open()
defer {
stream.close()
}
// Read data from .json file and transform data into an array
do {
guard let personArray = try JSONSerialization.jsonObject(with: stream, options: []) as? [[String: [String: String]]] else { return }
print(personArray) // prints [["person": ["name": "Dani", "age": "24"]], ["person": ["name": "ray", "age": "70"]]]
} catch {
print(error)
}
}
The Playground located in the Github's Save-and-read-JSON-from-Playground repo shows how to save a Swift Array
into a json file and how to read a json file and get a Swift Array
from it.