简体   繁体   中英

How to Store Data once I've encoded Codable Struct to JSON

I have an array of custom Plant Objects . Plant is Codable . I use JSONEncoder().encode() to get the array encoded in JSON , but how do I store this JSON , so that it can be saved once the app closes? I remember with NSCoder I could just encode it when the app closes and use the required convenience init? to decode it, but i don't see a similar option here. Here is my Singleton Class in which I am trying to save the [Plant]

import Foundation
public class Singleton{
    static let sInstance = Singleton(mPL: [Plant]())
    var myPlantList: [Plant]

    init(mPL: [Plant]){
        self.myPlantList = mPL
    }

    public func savePlants(){
        let jsonData = try? JSONEncoder().encode(myPlantList)
    }

}

Helper extensions..

import Foundation

public extension FileManager {
// Returns a URL that points to the document folder of this project.
    static var documentDirectoryURL: URL {
        return try! FileManager.default.url(
            for: .documentDirectory,
            in: .userDomainMask,
            appropriateFor: nil,
            create: false
        )
    }
}

Creating a folder that will contain your data file

let documentSubdirectoryURL = URL(
    fileURLWithPath: "MyFolder",
    relativeTo: FileManager.documentDirectoryURL
)
try? FileManager.default.createDirectory(
    at: documentSubdirectoryURL,
    withIntermediateDirectories: false
)

Saving -

do {
     let yourURL = URL(fileURLWithPath: "yourFileName", relativeTo: FileManager.documentDirectoryURL.appendingPathComponent("MyFolder")).appendingPathExtension("swift")
    ///ENCODE...
    try jsonData.write(to: yourURL)
}

Decode -

do {
    let yourURL = URL(fileURLWithPath: "yourFileName", relativeTo: FileManager.documentDirectoryURL.appendingPathComponent("MyFolder")).appendingPathExtension("swift")
    let jsonDecoder = JSONDecoder()
    let data = try Data.init(contentsOf: yourURL)
    let value = try jsonDecoder.decode([Plant].self, from: data)
  }

If you want to check the file containing your data, navigate to the url returned by

FileManager.documentDirectoryURL

试试jsonData.write(to:url)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM