I’ve written a function to save a playlist to a JSON file locally. However, when I try to parse it later, Xcode reports that the file does not exist at the specified path, even though the file is indeed there. What could be causing this issue?
Here is my code:
func savePlaylistData(lista: PlayListModel, _ playlistData: [PlaylistGroup: [PlaylistItem]], to filename: String) async throws {
// Create a temporary dictionary to hold the data with string keys
var tempDict: [String: [PlaylistItem]] = [:]
// Convert PlaylistGroup keys to string keys
for (key, value) in playlistData {
tempDict[key.groupName] = value
}
// Encode the dictionary to JSON
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted // To make the JSON human-readable
encoder.dateEncodingStrategy = .iso8601 // Ensure dates are encoded properly
// Perform the JSON encoding and file writing in a background thread
try await withCheckedThrowingContinuation { continuation in
do {
let jsonData = try encoder.encode(tempDict)
// Write the JSON data to a file with .txt extension
let fileURL = FileManager.default.temporaryDirectory.appendingPathComponent(filename).appendingPathExtension("json")
try jsonData.write(to: fileURL)
print("Data saved to (fileURL.path)")
continuation.resume()
// Update PlayListModel
lista.haveFile = true
lista.playlistUrl = fileURL.path
print("Updated PlayListModel with (fileURL.path)")
// Assuming modelContext is available and properly configured
do {
self.modelContext.insert(lista)
try modelContext.save()
} catch {
print("Failed to save PlayListModel: (error)")
}
} catch {
continuation.resume(throwing: error)
}
}
}
func loadPlaylistData(from url: URL) async throws -> [PlaylistGroup: [PlaylistItem]] {
// Debugging: Print the URL
// Debugging: Check if file exists
if FileManager.default.fileExists(atPath: url.path) {
print("File exists at (url.path)")
} else {
print("File does not exist at (url.path)")
throw NSError(domain: "FileError", code: 404, userInfo: [NSLocalizedDescriptionKey: "File does not exist at (url.path)"])
}
// Debugging: Check file readability
do {
let fileAttributes = try FileManager.default.attributesOfItem(atPath: url.path)
print("File attributes: (fileAttributes)")
} catch {
print("Error getting file attributes: (error.localizedDescription)")
throw NSError(domain: "FileError", code: 403, userInfo: [NSLocalizedDescriptionKey: "Cannot read file attributes at (url.path)"])
}
do {
// Read the JSON data from the file
print("Reading JSON data from the file at (url)")
let jsonData = try Data(contentsOf: url)
// Decode the JSON data into a temporary dictionary with String keys
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601 // Ensure dates are decoded properly
let tempDict: [String: [PlaylistItem]]
do {
tempDict = try decoder.decode([String: [PlaylistItem]].self, from: jsonData)
} catch let decodeError {
print("Failed to decode JSON data: (decodeError.localizedDescription)")
throw decodeError
}
// Convert the temporary dictionary back to the original format with PlaylistGroup keys
var playlistData: [PlaylistGroup: [PlaylistItem]] = [:]
for (key, value) in tempDict {
let group = PlaylistGroup(groupName: key)
playlistData[group] = value
}
return playlistData
} catch let dataError {
print("Failed to load and decode the file: (dataError.localizedDescription)")
throw dataError
}
}