gpt4 book ai didi

ios - 无法将 JSON 响应添加到 Realm

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:06:03 25 4
gpt4 key购买 nike

我正在尝试将我的 POST 响应添加到 Realm ,但我抛出了这个错误:

Cannot convert value of type 'String' to expected argument type 'Object'

这是我的代码:

     Alamofire.request(.POST, Data.loginEndpoint, parameters: parameters)
.responseObject { (response: Response<Particulars, NSError>) in

print(response.request)
print(response.response)
print(response.result)


if let result = response.result.value
{

do{
print(Realm.Configuration.defaultConfiguration.fileURL)
let realm = try Realm()
realm.add(result.name, update: true)
}

catch let err as NSError {
print("Error with realm: " + err.localizedDescription)
}

}
else
{
print("JSON data is nil. 123")
}
}

更新

我收到这个错误

fatal error: unexpectedly found nil while unwrapping an Optional value

user.name = result["name"]!.string

此外,我想从我的 do{}catch{} 中删除 !,但 swift 不允许我这样做。我如何解决它?

我的代码:

Alamofire.request(.POST, Data.loginEndpoint, parameters: parameters)
.responseObject { (response: Response<Particulars, NSError>) in

print(response.request)
print(response.response)
print(response.result)



if let result = response.result.value
{

do{
let user = Particulars()
user.name = result["name"]!.string
user.apiToken = result["api_token"]!.string
let realm = try Realm()
realm.add(user, update: true)
print(Realm.Configuration.defaultConfiguration.fileURL)
}

catch let err as NSError {
print("Error with realm: " + err.localizedDescription)
}

}
else
{
print("JSON data is nil. 123")
}
}

最佳答案

以下片段是直接从 Realm 文档中提取的。 Realm 需要一个继承自其“对象”类型的类对象。您必须创建一个类对象,其中包含您需要的所有属性(姓名、电子邮件等),并在收到响应时设置这些属性,然后将该对象保存到 Realm。

class Dog: Object {
dynamic var name = ""
dynamic var age = 0
}
class Person: Object {
dynamic var name = ""
dynamic var picture: NSData? = nil // optionals supported
let dogs = List<Dog>()
}

// Use them like regular Swift objects
let myDog = Dog()
myDog.name = "Rex"
myDog.age = 1
print("name of dog: \(myDog.name)")

// Get the default Realm
let realm = try! Realm()

// Query Realm for all dogs less than 2 years old
let puppies = realm.objects(Dog).filter("age < 2")
puppies.count // => 0 because no dogs have been added to the Realm yet

// Persist your data easily
try! realm.write {
realm.add(myDog)
}

关于ios - 无法将 JSON 响应添加到 Realm ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37427014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com