无法将值JSON转换为Alamofire和Sync中的AnyObject

时间:2015-11-25 06:38:27

标签: json swift

我正在使用Alamofire和SwiftyJSON来调用和API并获取JSON响应。我正在使用:

let responseJSON = JSON(response.result.value!)
let userDataJSON = responseJSON["userData"]

Sync.changes(
   userDataJSON,
   inEntityNamed: "User",
   dataStack: self.appDelegate.dataStack,
   completion: { (response ) -> Void in
      print("User \(response)")
})

尝试使用Hyperoslo Sync将响应同步到核心数据但我收到错误

Cannot convert value of type 'JSON' to expected argument type '[AnyObject]!'

由于

修改

Alamofire.request(Router.AuthenticateUser(postParameters))
   .validate(statusCode: 200..<300)
   .validate(contentType: ["application/json"])
   .responseJSON { response in
       if response.result.isSuccess {
          let responseJSON = JSON(response.result.value!)
          if let userDataJSON = responseJSON["userData"] {
             Sync.changes(
                [userDataJSON],
                inEntityNamed: "User",
                dataStack: self.appDelegate.dataStack,
                completion: { (response ) -> Void in
                    print("User \(response)")
                })
           }
...

Initializer for conditional binding must have Optional type, not 'JSON'

1 个答案:

答案 0 :(得分:-1)

根据文档Sync.changes语法:

Sync.changes(
  changes: [AnyObject]!,
  inEntityNamed: String!,
  dataStack: DATAStack!,
  completion: ((NSError!) -> Void)!)

它期望AnyObject的数组,并且您只传递不是数组的userDataJSON,因此像[userDataJSON]一样传递它。 还要检查userDataJSON是否是可选的,然后使用if或强制解包使用([userDataJSON]!)来安全解包。

所以试试,

Sync.changes(
   [userDataJSON]!,
   inEntityNamed: "User",
   dataStack: self.appDelegate.dataStack,
   completion: { (response ) -> Void in
      print("User \(response)")
})

if let userDataJSON = responseJSON["userData"] {
Sync.changes(
       [userDataJSON],
       inEntityNamed: "User",
       dataStack: self.appDelegate.dataStack,
       completion: { (response ) -> Void in
          print("User \(response)")
    })
}