Reputation: 384
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 advise 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)
}
}
}
}
Upvotes: 5
Views: 7922
Reputation: 4768
What I recommend is to use Codable objects, which means you can work in a more efficient and easier way to write/save json data files and load back to Codable objects.
Here is a small library that handles most of use cases with json files and data, its called CodableFiles. https://github.com/egzonpllana/CodableFiles
Upvotes: 1
Reputation: 11276
//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)")
}
})
}
Then while reading the file use the same constant...
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)")
}
}
Upvotes: 4