0
我的obj-c代码很好。 有人可以帮我弄清楚我的swift代码有什么问题吗?ios NSURLSession JSON解析到无快速(在obj-c中可用)
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];
和输出
2016-11-19 ...._block_invoke:39 status success reason updated
但是当我迅速的状态和原因实现它是零个
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()
我的网页输出
{"status":"success","reason":"updated","uuid":"blahblahblahbahaldsh"}
谢谢你能解开的自选项目。我想我现在明白了。我决定通过重写我的一个类而不是实际阅读语法来深入Swift。可能不是最好的主意。时间开始阅读.... – roocell