with json swift put alamofire

json - with - Cómo enviar una solicitud POST con BODY en swift



urlrequest post (10)

Así es como creé la solicitud Http POST con swift que necesita parámetros con codificación Json y con encabezados.

Se creó el Cliente API BKCAPIClient como una instancia compartida que incluirá todo tipo de solicitudes como POST, GET, PUT, DELETE, etc.

func postRequest(url:String, params:Parameters?, headers:HTTPHeaders?, completion:@escaping (_ responseData:Result<Any>?, _ error:Error?)->Void){ Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { response in guard response.result.isSuccess, (response.result.value != nil) else { debugPrint("Error while fetching data: /(String(describing: response.result.error))") completion(nil,response.result.error) return } completion(response.result,nil) } }

Clase de operación creada que contiene todos los datos necesarios para una solicitud particular y también contiene lógica de análisis dentro del bloque de finalización.

func requestAccountOperation(completion: @escaping ( (_ result:Any?, _ error:Error?) -> Void)){ BKCApiClient.shared.postRequest(url: BKCConstants().bkcUrl, params: self.parametrs(), headers: self.headers()) { (result, error) in if(error != nil){ //Parse and save to DB/Singletons. } completion(result, error) } } func parametrs()->Parameters{ return ["userid”:”xnmtyrdx”,”bcode":"HDF"] as Parameters } func headers()->HTTPHeaders{ return ["Authorization": "Basic bXl1c2VyOm15cGFzcw", "Content-Type": "application/json"] as HTTPHeaders }

Llame a la API en cualquier controlador de vista donde necesitemos estos datos

func callToAPIOperation(){ let accOperation: AccountRequestOperation = AccountRequestOperation() accOperation.requestAccountOperation{(result, error) in }}

Estoy tratando de hacer una solicitud de publicación con un cuerpo rápido usando Alamofire.

mi cuerpo json se ve así:

{ "IdQuiz" : 102, "IdUser" : "iosclient", "User" : "iosclient", "List":[ { "IdQuestion" : 5, "IdProposition": 2, "Time" : 32 }, { "IdQuestion" : 4, "IdProposition": 3, "Time" : 9 } ] }

Estoy tratando de hacer una list let con NSDictionnary que se vea así:

[[Time: 30, IdQuestion: 6510, idProposition: 10], [Time: 30, IdQuestion: 8284, idProposition: 10]]

y mi solicitud usando Alamofire se ve así:

Alamofire.request(.POST, "http://myserver.com", parameters: ["IdQuiz":"102","IdUser":"iOSclient","User":"iOSClient","List":list ], encoding: .JSON) .response { request, response, data, error in let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding) println(dataString) }

La solicitud tiene un error y creo que el problema está en la lista del Diccionario, porque si hago una solicitud sin la lista funciona bien, ¿alguna idea?

He intentado la solución sugerida pero estoy enfrentando el mismo problema:

let json = ["List":list,"IdQuiz":"102","IdUser":"iOSclient","UserInformation":"iOSClient"] let data = NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted,error:nil) let jsons = NSString(data: data!, encoding: NSUTF8StringEncoding) Alamofire.request(.POST, "http://myserver.com", parameters: [:], encoding: .Custom({ (convertible, params) in var mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest mutableRequest.HTTPBody = jsons!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) return (mutableRequest, nil) })) .response { request, response, data, error in let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding) println(dataString) }


Hay algunos cambios que me gustaría notificar. Puede acceder a la solicitud, JSON, error desde el objeto de respuesta de ahora en adelante.

let urlstring = "Add URL String here" let parameters: [String: AnyObject] = [ "IdQuiz" : 102, "IdUser" : "iosclient", "User" : "iosclient", "List": [ [ "IdQuestion" : 5, "IdProposition": 2, "Time" : 32 ], [ "IdQuestion" : 4, "IdProposition": 3, "Time" : 9 ] ] ] Alamofire.request(.POST, urlstring, parameters: parameters, encoding: .JSON).responseJSON { response in print(response.request) // original URL request print(response.response) // URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value { print("JSON: /(JSON)") } response.result.error }


He editado ligeramente la respuesta de SwiftDeveloper , porque no me funcionaba. También agregué la validación de Alamofire.

let body: NSMutableDictionary? = [ "name": "/(nameLabel.text!)", "phone": "/(phoneLabel.text!))"] let url = NSURL(string: "http://server.com" as String) var request = URLRequest(url: url! as URL) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let data = try! JSONSerialization.data(withJSONObject: body!, options: JSONSerialization.WritingOptions.prettyPrinted) let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue) if let json = json { print(json) } request.httpBody = json!.data(using: String.Encoding.utf8.rawValue) let alamoRequest = Alamofire.request(request as URLRequestConvertible) alamoRequest.validate(statusCode: 200..<300) alamoRequest.responseString { response in switch response.result { case .success: ... case .failure(let error): ... } }


No me gusta ninguna de las otras respuestas hasta ahora (excepto quizás la de SwiftDeveloper), porque requieren que deserialice su JSON, solo para que se serialice nuevamente, o que se preocupe por la estructura del JSON en sí.

La answer correcta ha sido publicada por afrodev en otra pregunta. Deberías ir y votarlo.

A continuación se muestra solo mi adaptación, con algunos cambios menores (principalmente juego de caracteres UTF-8 explícito).

let urlString = "https://example.org/some/api" let json = "{/"What/":/"Ever/"}" let url = URL(string: urlString)! let jsonData = json.data(using: .utf8, allowLossyConversion: false)! var request = URLRequest(url: url) request.httpMethod = HTTPMethod.post.rawValue request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type") request.httpBody = jsonData Alamofire.request(request).responseJSON { (response) in print(response) }


Si está utilizando swift4 y Alamofire v4.0 , el código aceptado se vería así:

let parameters: Parameters = [ "username" : email.text!, "password" : password.text! ] let urlString = "https://api.harridev.com/api/v1/login" let url = URL.init(string: urlString) Alamofire.request(url!, method: .put, parameters: , encoding: JSONEncoding.default, headers: nil).responseJSON { response in switch response.result { case .success(let json): let jsonData = json as! Any print(jsonData) case .failure(let error): self.errorFailer(error: error) } }


Si está utilizando Alamofire v4.0 +, la respuesta aceptada se vería así:

let parameters: [String: Any] = [ "IdQuiz" : 102, "IdUser" : "iosclient", "User" : "iosclient", "List": [ [ "IdQuestion" : 5, "IdProposition": 2, "Time" : 32 ], [ "IdQuestion" : 4, "IdProposition": 3, "Time" : 9 ] ] ] Alamofire.request("http://myserver.com", method: .post, parameters: parameters, encoding: JSONEncoding.default) .responseJSON { response in print(response) }


Usted está cerca. El formato del diccionario de parámetros no parece correcto. Deberías probar lo siguiente:

let parameters: [String: AnyObject] = [ "IdQuiz" : 102, "IdUser" : "iosclient", "User" : "iosclient", "List": [ [ "IdQuestion" : 5, "IdProposition": 2, "Time" : 32 ], [ "IdQuestion" : 4, "IdProposition": 3, "Time" : 9 ] ] ] Alamofire.request(.POST, "http://myserver.com", parameters: parameters, encoding: .JSON) .responseJSON { request, response, JSON, error in print(response) print(JSON) print(error) }

Esperemos que eso haya solucionado tu problema. Si no es así, responda y ajustaré mi respuesta en consecuencia.


{

if Reachability.isConnectedToNetwork() == true { let hud = MBProgressHUD.showAdded(to: self.view, animated: true) hud.mode = .indeterminate hud.label.text = "Loading" hud.animationType = .fade var request = URLRequest(url: URL(string: "http://skandal24.serv.si/ws/webservice/forgot_password")!) request.httpMethod = "POST" let postString = String(format: "email=%@&lang=%@", arguments: [txt_emailVirify.text!, language!]) print(postString) emailString = txt_emailVirify.text! request.httpBody = postString.data(using: .utf8) request.addValue("delta141forceSEAL8PARA9MARCOSBRAHMOS", forHTTPHeaderField: "Authorization") request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") Alamofire.request(request).responseJSON { response in //Your code print(response.value) if response.response?.statusCode == 200 { let dictionary = (response.value) as! AnyObject let status = dictionary.value(forKey: "status") as! String let sts = Int(status) DispatchQueue.main.async() { if sts == 200 { } } } else { } } } else { } }


Xcode 8.X, Swift 3.X

Uso fácil;

let params:NSMutableDictionary? = [ "IdQuiz" : 102, "IdUser" : "iosclient", "User" : "iosclient", "List": [ [ "IdQuestion" : 5, "IdProposition": 2, "Time" : 32 ], [ "IdQuestion" : 4, "IdProposition": 3, "Time" : 9 ] ] ]; let ulr = NSURL(string:"http://myserver.com" as String) let request = NSMutableURLRequest(url: ulr! as URL) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted) let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue) if let json = json { print(json) } request.httpBody = json!.data(using: String.Encoding.utf8.rawValue); Alamofire.request(request as! URLRequestConvertible) .responseJSON { response in // do whatever you want here print(response.request) print(response.response) print(response.data) print(response.result) }


func get_Contact_list() { ApiUtillity.sharedInstance.showSVProgressHUD(text: "Loading..") let cont_nunber = contact_array as NSArray print(cont_nunber) let token = UserDefaults.standard.string(forKey: "vAuthToken")! let apiToken = "Bearer /(token)" let headers = [ "Vauthtoken": apiToken, "content-type": "application/json" ] let myArray: [Any] = cont_nunber as! [Any] let jsonData: Data? = try? JSONSerialization.data(withJSONObject: myArray, options: .prettyPrinted) // var jsonString: String = nil var jsonString = String() if let aData = jsonData { jsonString = String(data: aData, encoding: .utf8)! } let url1 = "URL" var request = URLRequest(url: URL(string: url1)!) request.httpMethod = "POST" request.allHTTPHeaderFields = headers request.httpBody = jsonData as! Data // let session = URLSession.shared let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print("error=/(String(describing: error))") ApiUtillity.sharedInstance.dismissSVProgressHUD() return } print("response = /(String(describing: response))") let responseString = String(data: data, encoding: .utf8) print("responseString = /(String(describing: responseString))") let json = self.convertStringToDictionary(text: responseString!)! as NSDictionary print(json) let status = json.value(forKey: "status") as! Int if status == 200 { let array = (json.value(forKey: "data") as! NSArray).mutableCopy() as! NSMutableArray } else if status == 401 { ApiUtillity.sharedInstance.dismissSVProgressHUD() } else { ApiUtillity.sharedInstance.dismissSVProgressHUD() } } task.resume() } func convertStringToDictionary(text: String) -> [String:AnyObject]? { if let data = text.data(using: String.Encoding.utf8) { do { let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject] return json } catch { print("Something went wrong") } } return nil }