json - 无法在 Alamofire 和 Sync 中将值 JSON 转换为 AnyObject

标签 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'

最佳答案

根据文档 Sync.changes 语法:

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

它需要 AnyObject 数组,而您只传递 userDataJSON,它不是数组,所以像 [userDataJSON] 一样传递它。 还要检查 userDataJSON 是否是可选的,然后使用 if let 安全解包或使用 ([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)")
    })
}

关于json - 无法在 Alamofire 和 Sync 中将值 JSON 转换为 AnyObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33909960/

相关文章:

php - PHP 中的 json_encode 没有返回正确的结果

ios - 在 Watch InterfaceController.swift 中获取 MMWormhole 的未解析标识符

swift - 从您的应用程序发送带有 Swift 附加图像的电子邮件

java - 如何将对象序列化为 Jackson 中 ObjectNode 的值?

jquery - 处理数据传递的适当方法 MySQL->JSON->PHP?

ios - 无法在 Xcode 8.3.3 中解锁文件 “project.pbxproj”

ios - UIStackview 左对齐

ios - Swift:setObject 是 Parse 上的结构数组

ios - 如何确定 NSNumber 的真实数据类型?

javascript - 如何在 Google map 中使用动态纬度和经度值?