4

I'm working on transferring my project from AFNetworking to Alamofire. Really like the project. POST requests work just fine, however, I'm receiving this error when attempting to make a GET request.

Here's some example code:

class func listCloudCredntials(onlyNew onlyNew: Bool = true, includePending: Bool = true) -> Request {

    let parameters: [String: AnyObject] = includePending ? ["include_pending": "true"] : [:]

    let urlString = "https://myapp-staging.herokuapp.com/api/1/credntials"

    let token = SSKeychain.storedToken()

    let headers: [String: String] = ["Authorization": "Bearer \(token)"]

    return Alamofire.request(.GET, urlString, parameters: parameters, encoding: .JSON, headers: headers)
}

I receive this error: : -1005 The network connection was lost

However, if I change the request type to .POST, the request "works". I receive a 401 code, but at least the request doesn't lose Network connection.

What am I doing wrong?

Cody Winton
  • 2,989
  • 5
  • 25
  • 48

1 Answers1

18

You're encoding the parameters as JSON in the body of the request, try encoding the parameters in the URL by changing the encoding to URL:

return Alamofire.request(.GET, urlString, parameters: parameters, encoding: .URL, headers: headers)

As this is the default behavior, you can simply remove it:

return Alamofire.request(.GET, urlString, parameters: parameters, headers: headers)
redent84
  • 18,901
  • 4
  • 62
  • 85
  • Hi I am using `Alamofire.request (url, method: .post, parameters: parameters, headers: headers).responseJSON ` but i still get this error when i continuously hit API ..please help me.This error stressed me since the begining of Alamofire. – ami rt Aug 31 '17 at 05:07
  • @amirt Hey buddy, How did you solve that problem. I'm using the same method as yours, and got the error when I continuously hit APIs. My network is absolutely fine. – JsW Jan 18 '18 at 07:26
  • Still not find the solution, but for overcome this stressfull problem I just check Error_code == 1005 and hit api again. – ami rt Jan 18 '18 at 07:51