Multipart-form (image, parameters, encabezados) Solicitud de publicación con Alamofire in swift

En primer lugar, quiero decir que soy nuevo en cuanto a rapidez, y que conozco un poco. Por lo tanto, cualquier ayuda sería appriciated. Tengo una forma de datos multiparte que tiene una image (perfil-image), algunos parameters (nombre, apellido) y encabezados (ID de usuario, código hash). Quiero enviar una request POST para enviar el formulario.

He podido hacer una request POST solo con encabezados y otros parameters, excepto la image como:

let headers = [ "user_id": (Helper.getUserInfo()?.user_id)!, "hash_code":(Helper.getUserInfo()?.hash_code)!, ] let params = [ "name": self.name.text!, "address":self.address.text!] Alamofire.request(.POST, kFormUrl, parameters:params ,headers:headers).responseJSON { [weak self] response in //working fine } 

Pero cómo enviar la image como un file (no base-64string) es decir cargar files directamente con parameters y encabezados.

Gracias por adelantado

puede usar Alamofire 3.0+ debajo del código

 func uploadImageAndData(){ //parameters let gender = "M" let firstName = "firstName" let lastName = "lastName" let dob = "11-Jan-2000" let aboutme = "aboutme" let token = "token" var parameters = [String:AnyObject]() parameters = ["gender":gender,"firstName":firstName,"dob":dob,"aboutme":aboutme,"token":token,"lastName":lastName] let URL = "http://yourserviceurl/" let image = UIImage(named: "image.png") Alamofire.upload(.POST, URL, multipartFormData: { multipartFormData in if let imageData = UIImageJPEGRepresentation(image, 0.6) { multipartFormData.appendBodyPart(data: imageData, name: "image", fileName: "file.png", mimeType: "image/png") } for (key, value) in parameters { multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key) } }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): print("s") upload.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)") } } case .Failure(let encodingError): print(encodingError) } }) } 
  let userImageURL = NSURL(string: "your image url" as String) let data = NSData.init(contentsOfURL: userImageURL!) Alamofire.upload( .POST,registerUrl!, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data:"N".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"flag") multipartFormData.appendBodyPart(data: data!, name: "image", fileName: "pic.jpg", mimeType: "image/png") multipartFormData.appendBodyPart(data: facebookId.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"facebook_id") multipartFormData.appendBodyPart(data: nameString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"first_name") }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { response in print(response) let dict = response.result.value as! NSDictionary } case .Failure(let encodingError): print(encodingError) } } ) 

Utilizo Alamofire (Swift 2.3) para enviar varias partes con el progreso.

 func upload(URLRequest: Router, onProgress: (progress: Float?) -> Void, completion: (json: AnyObject?, error: Error?) -> Void) { let headers:[String: String] = [:] let router = URLRequest.URLRequest let tuple = URLRequest.parameters let parameters = tuple.0! let imagesData = tuple.1 let url = router.URLString self.manager!.upload( .POST, url, headers: headers, multipartFormData: { (multipartFormData: MultipartFormData) -> Void in for value in imagesData { var mimeType = "video/jpg" var bodyName = "images" let filename = value.uniqueName if value.mediaType == ReporterMediaType.image { mimeType = "image/jpg" bodyName = "images" } else if value.mediaType == ReporterMediaType.video { mimeType = "video/quicktime" bodyName = "video" } else if value.mediaType == ReporterMediaType.videoFrame { mimeType = "image/jpg" bodyName = "videoFrame" } multipartFormData.appendBodyPart( data: value.data, name: bodyName, fileName: filename, mimeType: mimeType) } for (key, value) in parameters { multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key) } }, encodingCompletion: { (encodingResult) -> Void in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { response in if response.result.isSuccess || response.response?.statusCode == 200 { completion(json: upload, error: nil) } else { dispatch_async(dispatch_get_main_queue()) { completion(json: nil, error: response.result.error) } } } upload.progress { _, totalBytesRead, totalBytesExpectedToRead in let progress = Float(totalBytesRead)/Float(totalBytesExpectedToRead) onProgress(progress: progress) } case .Failure: UIApplication.shanetworkingApplication().networkActivityIndicatorVisible = false break } }) }