[英]ios NSURLSession JSON parsing to nil in swift (ok in obj-c)
my obj-c code is fine. 我的obj-c代码很好。 can someone help me figure out what's wrong with my swift code? 有人可以帮我弄清楚我的快速代码怎么了吗?
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:url]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// handle response
if (error) {
TGLog(@"FAILED");
} else {
NSError* jsonerror;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonerror];
if (jsonerror != nil) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
TGLog(@"response status code: %ld", (long)[httpResponse statusCode]);
TGLog(@"%@", jsonerror);
return;
}
TGLog(@"%@", json);
TGLog(@"status %@ reason %@", [json objectForKey:@"status"], [json objectForKey:@"reason"]);
}
}] resume];
and outputs 和输出
2016-11-19 ...._block_invoke:39 status success reason updated
but when I implement it in swift status and reason are nil 但是当我以快速状态实施它时,原因为零
var request = URLRequest(url: url)
request.httpMethod = "POST"
URLSession.shared.dataTask(with: request) {data, response, err in
print("Entered user update completionHandler")
DispatchQueue.main.async() {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
if let error = err as? NSError {
print(error.localizedDescription)
} else if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: Any]
print(json)
let status = json["status"] as? [String:Any]
let reason = json["reason"] as? [String:Any]
// TODO: this is always printing out nil values - haven't figure out the swift problem yet
print("status \(status) reason \(reason)")
} catch let error as NSError {
print(error)
}
}
}
}.resume()
my webpage outputs 我的网页输出
{"status":"success","reason":"updated","uuid":"blahblahblahbahaldsh"}
Read the JSON, status
and reason
are String
rather than a dictionary 读取JSON, status
和reason
是String
而不是字典
let status = json["status"] as? String
let reason = json["reason"] as? String
According to the given JSON you could even cast json
to [String:String]
根据给定的JSON,您甚至可以将json
为[String:String]
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:String]
then you get rid of the other type casts 那么你就摆脱了其他类型的演员
let status = json["status"]
let reason = json["reason"]
The result of both lines is optional String
. 这两行的结果是可选的String
。 As you seem to be responsible for the web service you can unwrap the optionals if your service sends always the keys status
and reason
由于您似乎对Web服务负责,因此如果您的服务始终发送密钥status
和reason
则可以拆开可选项
let status = json["status"]!
let reason = json["reason"]!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.