无法将JSON响应添加到领域

时间:2016-05-25 02:53:23

标签: ios swift2 realm alamofire

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

  

无法将'String'类型的值转换为预期的参数类型'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")
            }
    }

更新

我收到此错误

  

致命错误:在解包可选值时意外发现nil

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")
            }
    }

1 个答案:

答案 0 :(得分:1)

以下代码片段是从Realm docs中直接提取的。 Realm想要一个继承自'Object'类型的类对象。您必须创建一个类对象,其中包含所需的所有属性(名称,电子邮件等),当您获得响应时设置这些属性,然后将该对象保存到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)
}