I get posts from Reddit API. I want to encode received JSON and write it to the local file. But after writing data to it, file is empty. Please advice how can I write encoded JSON data to the file or pretty JSON data.
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)
}
}
}
}
