ios - 无法将 JSON 响应添加到 Realm
<p><p>我正在尝试将我的 POST 响应添加到 Realm ,但我抛出了这个错误:</p>
<blockquote>
<p>Cannot convert value of type 'String' to expected argument type 'Object'</p>
</blockquote>
<p>这是我的代码:</p>
<pre><code> 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")
}
}
</code></pre>
<p><strong>更新</strong></p>
<p>我收到这个错误</p>
<blockquote>
<p>fatal error: unexpectedly found nil while unwrapping an Optional value</p>
</blockquote>
<p>在 <code>user.name = result["name"]!.string</code></p>
<p>另外,我想从我的 <code>do{} catch{}</code> 中删除 <code>!</code>,但 swift 不允许我这样做。我如何解决它? </p>
<p>我的代码:</p>
<pre><code>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")
}
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>以下代码段直接来自 Realm 文档。 Realm 需要一个继承自其“对象”类型的类对象。您必须创建一个具有所有您需要的属性(姓名、电子邮件等)的类对象,当您收到响应时设置这些属性,然后将该对象保存到 Realm。 </p>
<pre><code>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)
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - 无法将 JSON 响应添加到 Realm ,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/37427014/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/37427014/
</a>
</p>
页:
[1]