Postman request to Alamofire request

允我心安 提交于 2019-12-02 07:48:59

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)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!