如何使用CoreData?

时间:2018-07-13 21:06:44

标签: json swift3

我从API获取一些JSON数据,现在我想将其中一些数据保存在我的应用程序的CoreData中。我观看了一段视频,该视频演示了如何执行此操作,但是对我来说这是行不通的,我也不是为什么!

这是我的代码:

@IBAction func botaoSalvar(_ sender: Any) {

    let nomeUsuario = self.campoUsuario.text;
    let cpf = self.campoCPF.text;
    let senha = self.campoSenha.text;
    let plat = "ios"
    let method = "app-set-usuario"

    let param = ["nome": nomeUsuario, "cpf": cpf, "senha": senha, "method": method, "plataforma": plat]
    var _: HTTPHeaders = ["Content-Type": "application/json"]
    let url = "http://easypasse.com.br/gestao/wsCadastrar.php"

    Alamofire.request(url, method:.post, parameters:param, encoding: JSONEncoding.default).responseJSON { response in
        switch response.result {
        case .success:
            if let json = response.result.value as? [String: Any],
                let registro = json["registro"] as? [String: Any],
                let usuario = registro["usuario"] as? [String: Any],
                let nome = usuario["nome"] as? String {
                let cpf = usuario["cpf"] as? String
                let idusuario = usuario["idUsuario"] as? String

                let nomeUsuario: String = nome
                let cpfUsuario: String = cpf!
                let idUsuario: String = idusuario!

                let appDelegate = UIApplication.shared.delegate as! AppDelegate
                let context = appDelegate.persistentContainer.viewContext

                let dataUsuario = NSEntityDescription.insertNewObject(forEntityName: "Usuario", into: context)
                dataUsuario.setValue(nomeUsuario, forKey: "nome")
                dataUsuario.setValue(idUsuario, forKey: "idusuario")
                dataUsuario.setValue(cpfUsuario, forKey: "cpf")

                //Salvar os dados
                do {
                    try context.save()
                    print("Os dados foram salvos corretamente")
                } catch  {
                    print("Erro ao salvar os dados")
                }

            }

        case .failure(let error):
            print(0,"Error")
        }
    }

}

}

这是错误:

enter image description here

这是我的CoreData:

enter image description here

0 个答案:

没有答案