Search code examples
swifthttp-postalamofire

AlamoFire POST works but is returning NSURLErrorDomain error


I am using AlamoFire to post JSON to my web service and the post is working successfully and the values are submitted to the database, but AlamoFire is returning NSURLErrorDomain which then shows my 'submit failed' message. What am I doing wrong in the code below?

//AlamoFire POST
    var request = URLRequest(url: NSURL.init(string: URL)! as URL)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.timeoutInterval = 10 // secs
    request.httpBody = try! JSONSerialization.data(withJSONObject: myJson, options: [])

    Alamofire.request(request).responseJSON {
        (response) in
        log.info("HTTP RESPONSE: \(response.result)")
        if response.result.isSuccess {
            self.alertControllerMsg(msgStyle: UIAlertControllerStyle.alert,msgTitle: "Success", msgBody: "Update Delivered", cancelLbl: "", actionLbl: "Dismiss", complete: {
                self.view.endEditing(true)                    
                self.activityIndicator.stopAnimating()
                self.sendBtn.isEnabled = true
            })
        } else if response.result.isFailure {
            let error : Error = response.result.error!
            log.error(error)
            self.alertControllerMsg(msgStyle: UIAlertControllerStyle.alert,msgTitle: "Error", msgBody: "Update Failed. Please try again.", cancelLbl: "", actionLbl: "Dismiss", complete: {
                self.activityIndicator.stopAnimating()
                self.sendBtn.isEnabled = true
            })
        }
    }

EDIT: Here is the full error message:

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x170643540 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=http://{{URL.REDACTED}}/odata/Updates, NSErrorFailingURLKey=http://{{URL.REDACTED}}/odata/Updates, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}

Solution

  • I figured out that the issue was actually on the server side. The web service was receiving a URL parameter in addition to the HTTP BODY. Alamofire did not like that I was appending this parameter onto the URL. It must be how it is encoded because a similar call works in Fiddler but not through Alamofire. I plan to re-work the web service to remove the query string parameter.