Home > Software engineering >  How to archive data in swift?
How to archive data in swift?

Time:03-17

I am trying to archive data and want to store it in userdefault but app getting crash.

enter image description here

Also tried this

let encodedData = try NSKeyedArchiver.archivedData(withRootObject: selectedPoductDetails, requiringSecureCoding: false)

selectedPoductDetails is dict of type [String: SelectedProductDetail]

import Foundation

class SelectedProductDetail {

    let product: String
    var amount: Double
    var title: String

    init(product: String, amount: Double, title: String ) {
        self.product = product
        self.amount = amount
        self.title = title
    }
}

May i know why its not working and possible solution for same?

CodePudding user response:

As mentioned in the comments to use NSKeyedArchiver the class must adopt NSSecureCoding and implement the two required methods.

The types in your class are JSON compatible, so adopt Codable and archive the data with JSONEncoder (or PropertyListEncoder). You could even use a struct and delete the init method

struct SelectedProductDetail: Codable {

    let product: String
    var amount: Double
    var title: String
}

var productDetails = [String: SelectedProductDetail]()
// populate the dictionary 

do {
    let data = try JSONEncoder().encode(productDetails)
    UserDefaults.standard.set(data, forKey: "productDetails")
} catch {
    print(error)
}

Note:

UserDefaults is the wrong place for user data. It's better to save the data in the Documents folder

CodePudding user response:

For this case you can use UserDefaults

struct ProductDetail: Codable {
    //...
}

let encoder = JSONEncoder()

let selectedProductDetails = ProductDetail()

// Set
if let data = try? encoder.encode(selectedProductDetails) {
    UserDefaults.standard.set(data, forKey: "selectedProductDetails")
}

// Get
if let selectedProductDetailsData = UserDefaults.standard.object(forKey: "selectedProductDetails") as? Data {
    let selectedProductDetails = try? JSONDecoder().decode(ProductDetail.self, from: selectedProductDetailsData)
}
  • Related