Search code examples
iosswiftalamofirensurlrequest

Alamofire NSURLRequest via POST method doesn't work


I'm new to swift and iOS and trying to use Alamofire and router for them, which returns NSMutableURLRequest, but my code didn't work.
So I just made one NSURLRequest for test, and requested it but results was same. Here is my code. I'm currently using Alamofire and SwiftyJSON.

let params = ["Id": "1234567", "Token": "something"]
    let url = NSURL(string: "myurl")
    var request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = Alamofire.Method.POST.rawValue
    let encoding = Alamofire.ParameterEncoding.JSON
    (request, _) = encoding.encode(request, parameters: params)

Alamofire.request(request)
        .validate()
        .responseJSON { response in
            switch response.result {
            case .Success:
                if let value = response.result.value {
                    let json = JSON(value)
                    let token = json["token"].stringValue
                    let error = json["error"].stringValue
                    print("token : \(token), error : \(error)")
                }
            case .Failure(let error):
                // TODO:
                print(error)
            }
    }

Above code sends request without parameters. Are there any errors on my code?


Solution

  • I've checked your code and before executing encode function your request.HTTPBody is empty, but after it has some data like

    Optional<NSData> - Some:<7b22546f 6b656e22 3a22736f 6d657468 696e6722 2c224964 223a2231 32333435 3637227d>

    When I call print(response.request?.HTTPBody) in Alamofire response block, I get the parameters as NSData and the HTTPBody includes the same data as before sending the request so it works.

    Try also change the response from responseJSON to responseString, because if your response can't be parsed to JSON you get Failure.

    I think you should check on your URL site if you get correct data.

    Instead of your solution I use

    Alamofire.request(method, url, parameters: parameters, encoding: .JSON) .responseString{ response in}

    is the same but shorter and everything is as parameters.