2016-11-19 56 views
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"} 

回答

2

阅读JSON, statusreasonString,而不是一本字典

let status = json["status"] as? String 
let reason = json["reason"] as? String 

根据你甚至可以投json[String:String]

let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:String] 

然后你摆脱其他类型的投射

let status = json["status"] 
let reason = json["reason"] 
给定的JSON

两行的结果是可选的String。正如你似乎是负责Web服务,如果你的服务总是发送键statusreason

let status = json["status"]! 
let reason = json["reason"]! 
+0

谢谢你能解开的自选项目。我想我现在明白了。我决定通过重写我的一个类而不是实际阅读语法来深入Swift。可能不是最好的主意。时间开始阅读.... – roocell