如何在应用关闭时保存用户购物车? -迅速

问题描述 投票:0回答:1

我想在应用程序关闭时保存当前用户购物车,以便用户可以从相同状态返回。

我上这堂课:

class CarrinhoItem: NSObject, NSCoding {
    let produto: Item
    var qtd: Double

    // MARK: - Init

    init(_ produto: Item, _ qtd: Double) {
        self.produto = produto
        self.qtd = qtd
    }

    // MARK: - NSCoding
    func encode(with aCoder: NSCoder) {
        aCoder.encode(produto, forKey: "produto")
        aCoder.encode(qtd, forKey: "qtd")
    }

    required init?(coder aDecoder: NSCoder) {
        produto = aDecoder.decodeObject(forKey: "produto") as! Item
        qtd = aDecoder.decodeDouble(forKey: "qtd")

    }
}

而且我正在使用这些功能返回并保存购物车:

class CarrinhoDao {

    func save(_ Carrinho: [CarrinhoItem]) {
        guard let caminho = recuperaCaminho() else { return }
        do {
            let dados = try NSKeyedArchiver.archivedData(withRootObject: Carrinho, requiringSecureCoding: false)
            try dados.write(to: caminho)
        } catch {
            print(error.localizedDescription)
        }
    }

    func recupera() -> [CarrinhoItem] {
        guard let caminho = recuperaCaminho() else { return [] }
        do {
            let dados = try Data(contentsOf: caminho)
            guard let CarrinhoSalvo = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(dados) as? Array<CarrinhoItem> else { return [] }
            return CarrinhoSalvo
        } catch {
            print(error.localizedDescription)
            return []
        }
    }

    func recuperaCaminho() -> URL? {
        guard let diretorio = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil }
        let caminho = diretorio.appendingPathComponent("refeicao")

        return caminho
    }
}

我已将功能保存在AppDelegate上:

CartService.currentCart = [CarrinhoItem1,CarrinhoItem2,...]

fun applicationWillTerminate(_ application: UIApplication) {
        CarrinhoDao().save(CartService.currentCart)
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

但我遇到此错误:

unrecognized selector sent to instance 0x6000027f5780
The data couldn’t be written because it isn’t in the correct format.
ios swift save cart nscoding
1个回答
0
投票

Item是一个自定义类,因此您也必须对此类使用NSCoding协议

© www.soinside.com 2019 - 2024. All rights reserved.