Issue with Saving and Loading JSON Playlist in Swift

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
        }
    }
    


Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật