2016-11-19 66 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