【问题标题】:Cannot convert value JSON to AnyObject in Alamofire and Sync无法在 Alamofire 和 Sync 中将值 JSON 转换为 AnyObject
【发布时间】:2015-11-25 06:38:27
【问题描述】:

我正在使用 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 同步对 Core Data 的响应,但出现错误

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'

【问题讨论】:

  • 我对 sn-p 或 SwiftyJSON 了解不多,但 JSON 不是字典而不是数组吗?
  • 您的 userDataJSON 不是一个数组,您需要像 [userDataJSON] 一样传递参数,只需检查 userDataJSON 是否是可选的,然后使用 if let 或 force unwrap (!) 即 [userDataJSON] 安全地打开它!

标签: json swift


【解决方案1】:

根据文档 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'”错误
  • 使用不带 ! (强制展开)因为您的 userDataJSON 不是可选的。
  • 对不起,我还在学习这些东西,找不到明确的文档。我已经在上面添加了我的整个 Alamofire 代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多