Cómo analizar JSON en Swift usando NSURLSession

Estoy tratando de analizar JSON pero obtengo este error:

tipo de expresión es ambigua sin más contexto

Mi código es:

func jsonParser() { let urlPath = "http://headers.jsontest.com/" let endpoint = NSURL(string: urlPath) let request = NSMutableURLRequest(URL:endpoint!) let session = NSURLSession.sharedSession() NSURLSession.sharedSession().dataTaskWithRequest(request){ (data, response, error) throws -> Void in if error != nil { print("Get Error") }else{ //var error:NSError? do { let json:AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as? NSDictionary print(json) } catch let error as NSError { // error handling print(error?.localizedDescription) } } } //task.resume() } 

Esto funciona bien sin captura de prueba en Xcode 6.4, pero esto no funciona en Xcode 7.

No declare un tipo AnyObject para su objeto descodificado, ya que quiere que sea un NSDictionary y está realizando una conversión para hacerlo.

También es mejor utilizar cero opciones para la NSJSONSerialización en lugar de las aleatorias.

En mi ejemplo, también usé un tipo de error personalizado solo para demostración.

Tenga en cuenta que si está utilizando un tipo de error personalizado, también debe incluir una catch genérica para ser exhaustiva (en este ejemplo, con una simple bajada a NSError).

 enum JSONError: String, ErrorType { case NoData = "ERROR: no data" case ConversionFailed = "ERROR: conversion from JSON failed" } func jsonParser() { let urlPath = "http://headers.jsontest.com/" guard let endpoint = NSURL(string: urlPath) else { print("Error creating endpoint") return } let request = NSMutableURLRequest(URL:endpoint) NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in do { guard let data = data else { throw JSONError.NoData } guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary else { throw JSONError.ConversionFailed } print(json) } catch let error as JSONError { print(error.rawValue) } catch let error as NSError { print(error.debugDescription) } }.resume() } 

Lo mismo con Swift 3.0.2:

 enum JSONError: String, Error { case NoData = "ERROR: no data" case ConversionFailed = "ERROR: conversion from JSON failed" } func jsonParser() { let urlPath = "http://headers.jsontest.com/" guard let endpoint = URL(string: urlPath) else { print("Error creating endpoint") return } URLSession.shared.dataTask(with: endpoint) { (data, response, error) in do { guard let data = data else { throw JSONError.NoData } guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else { throw JSONError.ConversionFailed } print(json) } catch let error as JSONError { print(error.rawValue) } catch let error as NSError { print(error.debugDescription) } }.resume() } 

Apple declara aquí.

 func dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask 

Arreglalo:

 NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in // Your handle response here! } 

ACTUALIZAR:

 func jsonParser() { let urlPath = "http://headers.jsontest.com/" let endpoint = NSURL(string: urlPath) let request = NSMutableURLRequest(URL:endpoint!) NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in print(error) }.resume() } 

RESULTADO:

Opcional (dominio de error = NSURLErrorDomain Code = -1022 “El recurso no se pudo cargar porque la política de seguridad de transporte de aplicaciones requiere el uso de una conexión segura.” UserInfo = {NSUnderlyingError = 0x7f8873f148d0 {Error Domain = kCFErrorDomainCFNetwork Code = -1022 “(null ) “}, NSErrorFailingURLStringKey = http://headers.jsontest.com/ , NSErrorFailingURLKey = http://headers.jsontest.com/ , NSLocalizedDescription = No se pudo cargar el recurso porque la aplicaci \ u00f3n> Politica de Seguridad de Transporte requiere el uso de un conexión segura.})

¡Espero que esto ayude!

Esta es la forma más simple de analizar JSON utilizando NSUrlSession.

  let PARAMS = "{\"params1\":\"%@\",\"Params2\":\"%@\",\"params3\":\"%@\"}" let URL = "your url here" 

en el botón de enviar escribe este código.,

 let urlStr = String(format: "%@",URL) let jsonString = String(format:PARAMS, params1value,params2value,params3value ) // Encode your data here let jsonData = jsonString.data(using:.utf8) var request = URLRequest(url: URL(string: urlStr)!) request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") //set your method type here request.httpMethod = "POST" request.httpBody = jsonData let configuration = URLSessionConfiguration.default // create a session here let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main) let task = session.dataTask(with: request) {(data , response, error) in if(error != nil){ print("Error \(String(describing: error))") } else { do { let fetchedDataDictionary = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary print(fetchedDataDictionary!) let message = fetchedDataDictionary?["response key here"] as! String if message == "your response string" { print(message) } else { self.dataArray = (fetchedDataDictionary?["data"] as! NSArray) } } catch let error as NSError { print(error.debugDescription) } } } task.resume() 

Para el servicio web Swift 4 Llamar, publicar método utilizando URLSession

  func WebseviceCall(){ var request = URLRequest(url: URL(string: "YOUR_URL")!) request.httpMethod = "POST" let postString = "PARAMETERS" request.httpBody = postString.data(using: .utf8) request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print("error=\(error)") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(response)") } do { if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary { // Print out dictionary print(convertedJsonIntoDict) } } catch let error as NSError { print(error.localizedDescription) } } task.resume() } 

1) Haz la clase ApiConnection en tu proyecto … importa la clase Foundation ApiConnection: NSObject {

 class func postDataWithRequest(_ dicData:NSDictionary, completionHandler:@escaping (_ response:NSDictionary?,_ status:Bool)->Void) { let URL=Foundation.URL(string: Constant.API_URL) let request=NSMutableURLRequest(url: URL!) request.httpMethod="POST" request.addValue(Constant.kApplicationJSON, forHTTPHeaderField:Constant.kContentType) let data=try? JSONSerialization .data(withJSONObject: dicData, options: JSONSerialization.WritingOptions.prettyPrinted) request.httpBody=data //let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC)*5)) //dispatch_after(dispatchTime, dispatch_get_main_queue()) { let session = URLSession.shared.dataTask(with: request as URLRequest,completionHandler: { (data, response, error) in if error==nil { DispatchQueue.main.async(execute: { let dicResponse = try? JSONSerialization .jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary completionHandler(dicResponse, error==nil) }) } else { completionHandler(nil, error==nil) } }) session.resume() } } **********************************use this in your view controller**************** let dict : NSMutableDictionary = [:]; dict["Your key"] = "your value" dict["Your key"] = "your value" dict["Your key"] = "your value" ApiConnection.postDataWithRequest(dict) { (response, status) in if(status){ print(response); else{ print("failed webservice call"); } } 

************************************* Swift3.0 ********** ***************************

  var objDic = [String: Any]() let dic = NSMutableDictionary() print(dic) objDic["action"] = "" objDic["product_id"] = self.peroductid // arrProduct .addObjects(from: objDic) as! Dictionary print("\(objDic)") Alamofire.request(Constant.Webservice_productinfo, method: HTTPMethod.post, parameters:objDic as? Parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse) in switch(response.result) { case .success(_): if response.result.value != nil { let status = response2?.object(forKey: "status") as! String? if status == "error"{} //finding the status from response var response2 = response.result.value as AnyObject? self.response1 = response.result.value as! NSDictionary let type = (self.cartlistarray[0] as!NSDictionary)["base_image"] cell.productname.text = (self.cartlistarray[0] as!NSDictionary)["name"] as? String //Store the result value in swift 3.0 UserDefaults.standard.set(userDetail.value(forKey: "email") as? NSString, forKey: "email") if(UserDefaults.standard.object(forKey:"email") == nil){} //did select row click the data pass into another view let ProductListViewController = self.storyboard?.instantiateViewController(withIdentifier: "ProductListViewController") as! ProductListViewController ProductListViewController.category_id = ((self.bannerarry[0] as? [String : String])?["cat_id"])! //or else callin from indexpath.row item = ((cartlistarray[indexpath.row] as? NSDictionary)?.value(forKey:"product_id") as! String?)! 

extensión UIAlertController {

 func showErrorAlert(strMesage:NSString,VC:Any) { let alert = UIAlertController(title: "Demo App", message: strMesage as String, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) (VC as AnyObject).present(alert, animated: true, completion: nil) } 

} extensión UILabel {

 func setLabel(strTitle:String) { self.backgroundColor = UIColor.clear self.textColor = UIColor.white self.textAlignment = NSTextAlignment.left self.font = UIFont(name: "Avenir-Light", size: 15.0) self.font = UIFont.italicSystemFont(ofSize: 15) self.text=strTitle } 

}

  //image in to base 64 let image = imageCamera.image let imageData:NSData = UIImageJPEGRepresentation(image!, 1.0)!as NSData imageconvert = imageData.base64EncodedString(options: .lineLength64Characters) base64formate = imageconvert.trimmingCharacters(in:CharacterSet.whitespaces) print(base64formate) print data into profle view let imageurl:String! = SharedManager.sharedInstance().myMutableDict.value(forKey:"profileimg") as? String ?? "123" let url = URL(string: imageurl) DispatchQueue.global(qos: .userInitiated).async { let imageData:NSData = NSData(contentsOf: url!)! // When from background thread, UI needs to be updated on main_queue DispatchQueue.main.async { let image = UIImage(data: imageData as Data) self.imageview.image = image } } let actionSheetController: UIAlertController = UIAlertController(title: "Magento Extension App", message:response1?.object(forKey: "message") as? String, preferredStyle: .alert) actionSheetController.addAction(UIAlertAction(title: "Ok", style: .default , handler:{ (UIAlertAction)in print("Ok button click") })) self.present(actionSheetController, animated: true, completion: nil) } case .failure(_): print("error: \(response.result.error)") // original URL request break } } 

************************** objc *********************** ***************************

  NSDictionary *objDic1 = @{@"mode":@"loginUser", @"email":[result objectForKey:@"email"], @"password":@"", }; // With AFNetworking AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; [manager.requestSerializer setTimeoutInterval:100]; // manager set [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [manager POST:WEBSERVICE_CALL_URL parameters:objDic1 progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable result) { [SVProgressHUD dismiss]; NSLog(@"This s my response %@",result); NSLog(@"success!"); if ([[result valueForKey:kStatus] isEqualToString:kOK]) { } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { }]; ****************SDK LINK******************************************* https://github.com/AFNetworking/AFNetworking var userDetail = NSArray() userDetail = self.response1.value(forKey: "userData") as! NSArray print(userDetail) self.tmpDic = userDetail[0] as! NSDictionary print(self.tmpDic) var optionsdic = NSDictionary() optionsdic = self.tmpDic.value(forKey:"options") as! NSDictionary print(optionsdic) self.arrayOfKeys = optionsdic.allKeys as NSArray print(self.arrayOfKeys) if (self.arrayOfKeys.contains("color")) { print("color") self.colorarray = optionsdic.value(forKey:"color") as! NSArray print(self.colorarray.count) for index in 0..