我正在使用 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/