我正在用SRWebClient
库快速上传图片。
我的代码:
func uploadImage() {
let imageData:NSData = UIImageJPEGRepresentation(profilePicture.image, 100)
SRWebClient.POST("url")
.data(imageData, fieldName:"imagefile", data: ["username":self.username,"key":self.token])
.send({(response:AnyObject!, status:Int) -> Void in
println("result: \(response)")
//I have to parse result variable in here
},failure:{(error:NSError!) -> Void in
})
}
实际上效果很好。我从我的服务器返回json,我想解析它。但是我找不到如何从AnyObject
解析json吗?
这个代码的输出:
{"status":1,"picture":"e8ca745f511e8104fe2f920aab5d09c6.jpg"}
如何在response
变量中解析这个json?
发布于 2015-05-27 19:37:36
if let json = response as? [String : AnyObject] {
for key in json.keys {
if let intValue = json[key] as? Int {
// json[key] is an Int. Do something with intValue
} else if let stringValue = json[key] as? String {
// json[key] is a String. Do something with stringValue
}
}
}
发布于 2015-05-27 19:41:05
我查看了您正在使用的库,从第216 -221行( SRWebClient )中可以看到,JSON序列化是为您完成的:
let json:AnyObject? = NSJSONSerialization.JSONObjectWithData(result!, options: nil, error: &error)
if (error != nil && failure != nil) {
failure!(error)
} else if (json != nil && success != nil) {
success!(json, httpResponse!.statusCode)
}
因此,使用已经解析的JSON对象调用success。试着把它投到这样的字典里:
if let jsonResponse = response as? [String: AnyObject] {
// do whatever needs to be done with the dictionary here
}
而传递的状态是一个HTTP状态码。
https://stackoverflow.com/questions/30491499
复制相似问题