Postman request to Alamofire request

后端 未结 1 1181
逝去的感伤
逝去的感伤 2021-01-27 16:57

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

相关标签:
1条回答
  • 2021-01-27 17:41

    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)
    }
    
    0 讨论(0)
提交回复
热议问题