我从 Reddit API 获取帖子。我想对收到的 JSON 进行编码并将其写入本地文件。但写入数据后,文件为空。请告知如何将编码的 JSON 数据写入文件或漂亮的 JSON 数据。
class Utils {
func saveToJSON() {
UseCase().createPosts(sub: "ios", limit: 5, completion: { posts in
print(posts)
let filePath = self.getDocumentsDirectoryUrl().appendingPathComponent("landmarkData.json")
print(filePath)
do {
let jsonData = try JSONEncoder().encode(posts)
print(jsonData)
try jsonData.write(to: filePath)
// here landmarkData.json file is empty
} catch {
print("Error writing to JSON file: \(error)")
}
})
}
func getDocumentsDirectoryUrl() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
}
struct RedditPost: Hashable, Codable, Identifiable {
var username: String
var createdHoursAgo: String
var domain: String
var title: String
var text: String
var imageURL: String
var downs: Int
var ups: Int
var rating: Int { ups - downs }
var comments: Int
var saved: Bool = false
var id: String
}
class UseCase {
func createPosts(sub: String, limit: Int, completion: (@escaping (_ data: [RedditPost]) -> Void)) {
Repository().fillPostsArray(sub: sub, limit: limit) { (redditPosts: [RedditPost]) in
DispatchQueue.main.async {
completion(redditPosts)
}
}
}
}
//Define globally..
let fileName = "landmarkData.json"
func saveToJSON() {
UseCase().createPosts(sub: "ios", limit: 5, completion: { posts in
print(posts)
let filePath = self.getDocumentsDirectoryUrl().appendingPathComponent(fileName)
print(filePath)
do {
let jsonData = try JSONEncoder().encode(posts)
print(jsonData)
try jsonData.write(to: filePath)
// here landmarkData.json file is empty
} catch {
print("Error writing to JSON file: \(error)")
}
})
}
然后在读取文件时使用相同的常量...
func readFromJson() {
let filePath = self.getDocumentsDirectoryUrl().appendingPathComponent(fileName)
print(filePath)
do {
let jsonData = try JSONDecoder().decode(posts)
print(jsonData)
} catch {
print("Error reading from JSON file: \(error)")
}
}
我推荐的是使用Codable对象,这意味着你可以以更高效、更简单的方式编写/保存json数据文件并加载回Codable对象。
这是一个小型库,可以处理大多数 json 文件和数据的用例,它称为 CodableFiles。 https://github.com/egzonpllana/CodableFiles