//This JSON {"data":[{"id":288,"eid":16,"admin":true},{"id":289,"eid":16,"admin":false}],"meta":{"count":2}}
Alamofire.request(self.url, headers: header).responseJSON
(completionHandler: { response in
statusCode = (response.response?.statusCode)!
if statusCode != 200{
}else{
switch response.result {
case .success( let responseJSON):
let json = JSON(responseJSON)
print(json)
let data = json["data"]
print(data)
case .failure(_):
print("ERROR")
}
}
})
}
}
}
I am using alamofire for some time now, but I have never used a form data Post. Now I am stuck. I have 2 params (email, password) and don't know how POST them to server. Can anyone give me an example please?
And here is a sample code for Alamofire 4.0 in Swift 3.0
let url = "http://testurl.com"
let parameters = [
"email": "asd#fgh.hjk",
"password": "55555"
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default).responseJSON { response in
switch response.result {
case .success:
if let value = response.result.value {
print(value)
}
case .failure(let error):
print(error)
}
}
So my solution is.... you have to specify the Parameter Encoding in Alamofire. So the code will look like this.
Swift 2.0
func registerNewUserFormData(completionHandler: (Bool, String?) -> ()){
// build parameters
let parameters = ["email": "test#test.cz", "password": "123456"]
// build request
Alamofire.request(.POST, urlDomain + "register", parameters: parameters, encoding: .URL).responseJSON { response in
switch response.result {
case .Success:
print("Validation Successful")
if let JSON = response.result.value {
print(JSON)
}
case .Failure(let error):
print(error)
}
}
}
Swift 5
let url = "http://testurl.com"
let parameters = [
"email": "asd#fgh.hjk",
"password": "55555"
]
AF.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default).responseJSON { response in
switch response.result {
case .success:
if let value = response.result.value {
print(value)
}
case .failure(let error):
print(error)
}
}
I am converting an project from Swift 1.1 to Swift 2.0 that used Alamofire 1.3.
Because this version of Alamofire was not compatible with Swift 2.0, I switched to the very last version of Alamofire (3.1.x).
However this broke the code, I am now getting the error message
"Cannot call value of non-function type 'NSHTTPURLResponse?'"
which is due to my my extension to create a custom "responseShop" Alamofire.Request.
How can this Alamofire.Request extension correctly be converted to the Alamofire 3.x/Swift 2.0 syntax?
extension Alamofire.Request {
func responseShop(options: NSJSONReadingOptions = .AllowFragments, var errorHandler:ProtocolWebServiceErrorHandler?, completionHandler: (ShopCallResult?, WebServiceErrorCode) -> Void ) -> Self {
objc_sync_enter(communicationLockObj)
return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: {
(request, response, JSON, error) in
log.verbose("\(JSON)")
//network error?
if let error = error {
//is it cancelled?
if error.code == -999 {
dispatch_async(dispatch_get_main_queue()) {
//call handler with cancelled code
completionHandler(nil, WebServiceErrorCode.requestCancelled)
}
objc_sync_exit(communicationLockObj)
return
}
dispatch_async(dispatch_get_main_queue()) {
errorHandler?.handleWebServiceError(WebServiceErrorCode.connectError, errorText : error.localizedDescription, request: request, json: JSON)
//call and supply org error
completionHandler(nil, WebServiceErrorCode.connectError)
}
objc_sync_exit(communicationLockObj)
return
}
if JSON == nil {
dispatch_async(dispatch_get_main_queue()) {
errorHandler?.handleWebServiceError(WebServiceErrorCode.jsonNil, errorText: nil, request: request, json: JSON)
//call and supply org error
completionHandler(nil, WebServiceErrorCode.jsonNil)
}
objc_sync_exit(communicationLockObj)
return
}
//api return error?
let callResult = ShopCallResult(json: JSON!)
if callResult.statusCode.failed {
dispatch_async(dispatch_get_main_queue()) {
errorHandler?.handleWebServiceError(callResult.statusCode, errorText: callResult.statusCode.localizedText, request: request, json: JSON)
completionHandler(callResult, callResult.statusCode)
}
objc_sync_exit(communicationLockObj)
return
}
//no error
dispatch_async(dispatch_get_main_queue()) {
completionHandler(callResult, WebServiceErrorCode.OK)
}
objc_sync_exit(communicationLockObj)
})
return self
}
}
Based on the feedback of #ProblemSolver I managed to convert the code, now it looks like this:
extension Alamofire.Request {
func responseShop(queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, errorHandler:ProtocolWebServiceErrorHandler?, completionHandler: (ShopCallResult?, WebServiceErrorCode) -> Void ) -> Self {
//enter thread protected area...
objc_sync_enter(communicationLockObj)
return responseJSON() {
response in
switch response.result {
case .Success(let JSON):
//log json in verbose mode
log.verbose("\(JSON)")
//parse the returned json
let callResult = ShopCallResult(json: JSON)
//is it failed?
if callResult.statusCode.failed {
//call supplied error handler on the main thread
dispatch_async(dispatch_get_main_queue()) {
errorHandler?.handleWebServiceError(callResult.statusCode, errorText: callResult.statusCode.localizedText, request: self.request!, json: JSON)
completionHandler(callResult, callResult.statusCode)
}
//release the lock
objc_sync_exit(communicationLockObj)
//processing done!
return
}
//no error call handler on main thread
dispatch_async(dispatch_get_main_queue()) {
completionHandler(callResult, WebServiceErrorCode.OK)
}
//release the lock
objc_sync_exit(communicationLockObj)
case .Failure(let error):
//WARNING: cancelled is still error code 999?
//is it cancelled?
if error.code == -999 {
//just call the completion handler
dispatch_async(dispatch_get_main_queue()) {
//call handler with cancelled code
completionHandler(nil, WebServiceErrorCode.requestCancelled)
}
//release the lock
objc_sync_exit(communicationLockObj)
//stop furhter processing
return
}
//error with the json?
if error.code == Alamofire.Error.Code.JSONSerializationFailed .rawValue {
//call the error handler
dispatch_async(dispatch_get_main_queue()) {
errorHandler?.handleWebServiceError(WebServiceErrorCode.jsonNil, errorText: nil, request: self.request!, json: nil)
//call and supply org error
completionHandler(nil, WebServiceErrorCode.jsonNil)
}
//release the lock
objc_sync_exit(communicationLockObj)
//stop further processing
return
}
//must be some other kind of network error
dispatch_async(dispatch_get_main_queue()) {
log.error("\(error)")
//so call the error handler
errorHandler?.handleWebServiceError(WebServiceErrorCode.connectError, errorText : error.localizedDescription, request: self.request!, json: nil)
//call and supply org error
completionHandler(nil, WebServiceErrorCode.connectError)
}
//release the lock
objc_sync_exit(communicationLockObj)
}
}
}
}
This code work before migrate to Swift 2.0 and Alamofire 2.0
manager.upload(requestMethod, NSURL(string: url)!, multipartFormData: { multipartFormData in
for param in params {
multipartFormData.appendBodyPart(data: param.1.dataUsingEncoding(NSUTF8StringEncoding)!, name: param.0)
}
multipartFormData.appendBodyPart(data: imageData!, name: "file", fileName: "tempImage", mimeType: "image/*") },
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { _, response, result in
switch result {
case .Success(let data):
...
case .Failure(let encodingError):
...
}
}
case .Failure(let encodingError):
...
}
} )
Now the line:
upload.responseJson...
always return fail "FAILURE: Error Domain=NSURLErrorDomain Code=-999 "cancelled" "
Someone has managed to use the multipart in Alamofire 2.0 successfully and know what am I doing wrong?
In my case it had to do with additional headers. I put general headers like this:
var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
defaultHeaders["User-Agent"] = userAgent
if let ip = ifAddress {
defaultHeaders["X-Forwarded-For"] = ip
}
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = defaultHeaders
manager = Alamofire.Manager(configuration: configuration)
And for additional headers that depend on a specific condition I put in the request itself:
if condition {
headers = ["Accept": contentType]
}
manager!.request(requestMethod, url, parameters: params, headers: headers).responseJSON { response in
…
I am developing an iPhone application with swift. and I'am using Alamofire framework for handling http requests. I use Alamofire.request for POST , GET and etc like this:
Alamofire.request(.POST, myURL , parameters: ["a": "1", "b" : "2" ])
.response { (request, response, data, error) in
}
And I use Alamofire.upload to upload image to server this :
Alamofire.upload(.POST, uploadURL , fileURL)
And both works perfectly, but now I want to upload an image and also send some parameters with, and my content type should be multipart/form-data and Alamofire.upload does not accept parameters.
There are two more question on SO about this issue with swift, which first one is not using Alamofire (and really, why not?) and in second one, mattt (Alamofire Developer) cited to use encoding parameters.
I checked his example, but still couldn't figure out how to do that.
Can any one please help me solve this problem?
Thank you! :)
you can use Alamofire 3.0+ below code
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":about,
"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)
}
})
}
SWIFT 2 AlamoFire Simple Image Upload (REST API)
#amit gupta It seems answer contains big overhead. AlamoFire contain load of simplified solution. Alamofire.request method contains several simplified overload which can use to upload in simple manner. By using Alamofire.request( method developer can get rid of encoding overhead.
HTTP Status 415 gives because of not specifying the correct media type.
Please check my solution below.
import UIKit
import Alamofire
class ViewController: UIViewController {
#IBOutlet var imageView: UIImageView!
#IBOutlet var btnUpload: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
func successDataHandler(responseData:String){
print ("IMAGE UPLOAD SUCCESSFUL !!!")
}
func failureDataHandler(errorData:String){
print (" !!! IMAGE UPLOAD FAILURE !!! ")
}
#IBAction func actionUpload(sender: AnyObject) {
let URL = "http://m8coreapibeta.azurewebsites.net/api/cards/SaveImages"
let postDataProlife:[String:AnyObject] = ["CardId":(dataCardDetail?.userId)!,"ImageType":1,"ImageData":imageView.image!]
uplaodImageData(URL, postData: postDataProlife, successHandler: successDataHandler, failureHandler: failureDataHandler)
}
func uplaodImageData(RequestURL: String,postData:[String:AnyObject]?,successHandler: (String) -> (),failureHandler: (String) -> ()) -> () {
let headerData:[String : String] = ["Content-Type":"application/json"]
Alamofire.request(.POST,RequestURL, parameters: postData, encoding: .URLEncodedInURL, headers: headerData).responseString{ response in
switch response.result {
case .Success:
print(response.response?.statusCode)
successHandler(response.result.value!)
case .Failure(let error):
failureHandler("\(error)")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Almaofire with swift 3.0
Alamofire.upload(multipartFormData: { multipartFormData in
var index = 1
for image in imageArray {
let imageData: Data = (UIImageJPEGRepresentation(image, 1.0) as Data?)!
multipartFormData.append(imageData, withName: "home-\(index)", fileName: "home-\(index)", mimeType: "image/jpeg")
index += 1
}
}, with: requestName, encodingCompletion: { result in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
print("Image(s) Uploaded successfully:\(response)")
}
case .failure(let encodingError):
print("encodingError:\(encodingError)")
}
})
Swift 4 with Alamofire 4
let isConnected = connectivity.isConnectedToInternet()
func updateProfile(firstName:String,lastName:String ,imageData:Data?,completion: #escaping (isValidUser)->()) {
if self.isConnected {
var parameters : [String:String] = [:]
parameters["auth_key"] = loginUser?.authKey!
parameters["first_name"] = firstName
parameters["last_name"] = lastName
let url = "\(baseUrl)\(basicAuthenticationUrl.updateProfile)"
print(url)
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
if let data = imageData {
multipartFormData.append(data, withName: "image_url", fileName: "image.png", mimeType: "image/png")
}
}, usingThreshold: UInt64.init(), to: url, method: .post) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
print("Succesfully uploaded = \(response)")
if let err = response.error{
print(err)
return
}
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
}
}
}
}
Almaofire with swift 2.0 just copy and paste below code.here m asumming JSON response from server
func uploadImageRemote (imageData : NSData?) -> Dictionary <String,AnyObject>{
var imageDictionary = Dictionary<String,AnyObject>()
var tokenHeaders:[String:String]! = ["x-access-token":Constants.kUserDefaults.stringForKey("userToken")!]
Alamofire.upload(
.POST,
"http://52.26.230.146:3300/api/profiles/imageUpload",headers:tokenHeaders,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imageData!, name: "upload", fileName: "imageFileName.jpg", mimeType: "image/jpeg")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
print("Uploading Avatar \(totalBytesWritten) / \(totalBytesExpectedToWrite)")
dispatch_async(dispatch_get_main_queue(),{
})
}
upload.responseJSON { response in
guard response.result.error == nil else {
print("error calling GET \(response.result.error!)")
return
}
if let value = response.result.value {
print("Success JSON is:\(value)")
if let result = value as? Dictionary<String, AnyObject> {
imageDictionary["imageUrl"] = result["url"]
}
}
dispatch_async(dispatch_get_main_queue(),{
//Show Alert in UI
print("Avatar uploaded");
})
}
case .Failure(let encodingError):
//Show Alert in UI
print("Avatar not uploaded \(encodingError)");
}
}
);
return imageDictionary
}
To use encoding Parameters, make a ParameterEncoding variable, assign it a encoding type (case of the enum which include .JSON, .URL) and then use the encode function with your NSURLRequest and the parameters. This function returns a tuple of two element, the first being the resulting NSURLRequest and the second being the resulting possible NSError.
Here's how I used it for a custom header I needed in a project
var parameterEncoding:ParameterEncoding!
switch method {
case .POST, .PUT :
parameterEncoding = ParameterEncoding.JSON
default :
parameterEncoding = ParameterEncoding.URL
}
var alamoRequest = Alamofire.Manager.sharedInstance.request(parameterEncoding.encode(mutableURLRequest, parameters: parameters).0)