user1990406 user1990406 - 2 months ago 25
Swift Question

Postman request to Alamofire request

I'm having no issues when I make the post request with POSTMAN but when I use alamofire I have issues. The post still goes through on the alamofire request but the data is not received the same way. What does an alamofire request look like that's the exact same as the following postman...

enter image description here

Answer

Swift 2.x:

typealias apiSuccess = (result: NSDictionary?) -> Void
typealias apiProgress = (result: NSDictionary?) -> Void // when you want to download or upload using Alamofire..
typealias apiFailure = (error: NSDictionary?) -> Void

// Normal http request with JSON response..
func callJSONrequest(url:String, params:[String: AnyObject]?, success successBlock :apiSuccess,
                     failure failureBlock :apiFailure) {

    Alamofire.request(.POST, url, parameters: params, encoding: ParameterEncoding.URL)
        .responseJSON { response in
            print("\(response.request?.URL)")  // original URL request
            //print(response.response) // URL response
            //print(response.data)     // server data
            //print(response.result)   // result of response serialization
            if response.result.isSuccess {
                let jsonDic = response.result.value as! NSDictionary
                successBlock(result: jsonDic)

            } else {
                let httpError: NSError = response.result.error!
                let statusCode = httpError.code
                let error:NSDictionary = ["error" : httpError,"statusCode" : statusCode]
                failureBlock(error: error)
            }
    }
}

func myFunction() {
    let myApiSuccess: apiSuccess = {(result: NSDictionary?) -> Void in
        print ("Api Success : result is:\n \(result)")
        // Here you can make whatever you want with result dictionary
    }

    let myApiFailure: apiFailure = {(error: NSDictionary?) -> Void in
        print ("Api Failure : error is:\n \(error)")
        // Here you can check the errors with error dictionary looking for http error type or http status code
    }
    var params :[String: AnyObject]?
    let email : String! = "stuart@gmail.com"
    let password : String! = "thisismypassword"
    params = ["email" : email, "password" : password]
    let url : String! = "https://arcane-brook-75067.herokuapp.com/login"
    callJSONrequest(url, params: params, success: myApiSuccess, failure: myApiFailure)
}