簡體   English   中英

如何寫入和讀取 applicationSupportDirectory 中的 JSON 文件? (迅速)

[英]How do I write and read to a JSON file inside the applicationSupportDirectory? (Swift)

我正在嘗試將結構保存為應用程序的 applicationSupportDirectory 中的 JSON 文件,然后稍后將其讀取到不同文件中的不同變量。 但是,當我之后嘗試解碼和讀取該文件時,我得到了一個

typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

這些是我的結構

struct Event: Codable, Identifiable{
    var id: Int
    var name: String
    var organization: String
    var location: String
    var description: String
    
    private var imageName: String
    
    var image: Image{
        Image(imageName)
    }
    
    private var coordinates: Coordinates
    
    var locationCoordinate: CLLocationCoordinate2D {
        CLLocationCoordinate2D(
            latitude: coordinates.latitude,
            longitude: coordinates.longitude)
    }
    
    init(id: Int, name: String, organization: String, location: String, description: String, imageName: String, coordinates: Coordinates) {
        self.id = id
        self.name = name
        self.organization = organization
        self.location = location
        self.description = description
        self.imageName = imageName
        self.coordinates = coordinates
    }
    
}

struct Coordinates: Hashable, Codable {
    var latitude: Double
    var longitude: Double
}

這就是我將事件保存在 appDirectory 中的方式:

func saveDataToSupportDirectory( event: Event) {
   
    do {
        let fileURL = try FileManager.default
            .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
            .appendingPathComponent("eventData.json")

        try JSONEncoder().encode(event).write(to: fileURL)
        } catch {
            print(error)
        }
}

這就是我在成功運行saveDataToSupportDirectory后在不同文件中讀取它的方式。 好吧,至少我相信它是成功的,因為它沒有顯示錯誤。 老實說,我不知道如何查看該目錄中的文件。

var events: [Event] = load("eventData.json")

func load<T: Decodable>(_ filename: String) -> T {
    let data: Data

    //Load the file into data
    do {
        let fileURL = try FileManager.default
            .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
            .appendingPathComponent("eventData.json")
        data = try Data(contentsOf: fileURL)
    } catch {
        fatalError("Couldn't load data")
    }
    
    do{
        return try JSONDecoder().decode(T.self, from: data)
    }
    catch{
        print(error)
        fatalError("Couldn't decode data")
    }

}

您必須匹配您嘗試編碼和解碼的類型。 在我的示例中,我嘗試對單個 object 事件進行編碼並解碼事件數組。 感謝@jnpdx!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM