Alamofire Request error only on GET requests - ios

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?

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)

Related

NSLocalizedDescription=The certificate for this server is invalid Alamofire 5.2 Swift

I am trying to create a login screen which uses Alamofire 5.2 to post the request but I seem to get the same error over and over again, I have tried to set up the info.plist file as many have suggested bu it was of no help. I tried to change the method in which I will post which was also of no help.
Please help Me our with this as I have been stuck with this for days with no results.
Request Function:
func loginPlease(){
let params = ["username":self.emailTextBox.text!, "password":self.PasswordTextBox.text!]
let encodeURL = "domain url"
let requestoAPI = AF.request(encodeURL, method: .post, parameters: nil, encoding: JSONEncoding.default, headers:["username":self.emailTextBox.text!, "password":self.PasswordTextBox.text!])
requestoAPI.responseJSON(completionHandler: { (response) -> Void in
print(response.request!)
print(response.result)
print(response.response)
})
}
Alternative function (just to be sure)
func loginPlease(){
let params = ["username":self.emailTextBox.text!, "password":self.PasswordTextBox.text!]
let encodeURL = "domain url"
let requestoAPI = AF.request(encodeURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers:nil)
requestoAPI.responseJSON(completionHandler: { (response) -> Void in
print(response.request!)
print(response.result)
print(response.response)
})
}
Info.plist:
Log:

Swift 5 & Alamofire 5 : GET method ERROR: Alamofire.AFError.URLRequestValidationFailureReason.bodyDataInGETRequest(22 bytes)

I am trying to get records from Database using Alamofire. I am sending parameters in GET request as below.
let headers : HTTPHeaders = ["x-access-token": "\(t)","username":"\(Base.sharedManager.user)","password":"\(Base.sharedManager.pass)"]
let parm : [String: Any] = ["search_str" : self!.searchStr]
// let searchUrl = Base.sharedManager.URL+"questions/get/"+self!.searchStr
let searchUrl = Base.sharedManager.URL+"questions/get/"
AF.request(searchUrl, method: .get, parameters: parm, encoding:JSONEncoding.default , headers: headers, interceptor: nil).response { (responseData) in
guard let data = responseData.data else {
debugPrint("Error getting question data", responseData.error as Any)
self?.showNoResults()
return
}
do {
let sResults = try JSONDecoder().decode(SearchResults.self, from: data)
self!.searchReturn = [sResults]
self!.qSearchTV.reloadData()
} catch {
self?.showNoResults()
print("Error retriving questions \(error)")
}
}
Got the error below when above code executed:
"Error getting question data" Optional(Alamofire.AFError.urlRequestValidationFailed(reason: Alamofire.AFError.URLRequestValidationFailureReason.bodyDataInGETRequest(23 bytes)))
Use URLEncoding.default instead of JSONEncoding.default
AF.request(path,
method: .get,
parameters: params,
encoding: URLEncoding.default,
headers: nil)
.response { (responseData) in
}
Alamofire 5 and Apple's 2019 frameworks now produce an error when you try to make a GET request with body data, as such a request is invalid. I would suggest checking to make sure that's what your server is expecting, and if it does really require body data for GET requests, reach out to the API provider and request a change, as no device running Apple's 2019 OSes will be able to make such a request.
You have to remove the "parameters" parameter.
Instead of doing this:
AF.request("https://httpbin.org/get",
method: .get,
parameters: [:],
encoding: URLEncoding.httpBody,
headers: [:])
Do this:
AF.request("https://httpbin.org/get",
method: .get,
encoding: URLEncoding.httpBody,
headers: [:])

Alamofire 4.4.0: Extra Argument 'Method' in Call: Do not know What is Throwing Error

I have an alamofire request in swift and am not sure why it is throwing Extra Argument 'Method' in Call:
Alamofire.request(
URL(string: "https://api.io"),
method: .post,
parameters: [
"grant_type": "client_credentials",
"client_id": "user00941",
"client_secret": "ILGddu8y8g7qW"
],
encoding: .urlEncodedInURL
).response {
request, response, data, error in
let json = JSON(data: data!)
print("OAuth 2 token obtained from API: \(json["access_token"])")
let token = "Bearer \(json["access_token"].stringValue)"
}
I have been looking at various other posts but cannot seem to find one with a solution that fits my code.
The problem with your original code was that you were using the argument label url even though the Alamofire.request function signature has omitted it:
public func request(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
-> DataRequest
Removing url: from your function call will take care of that error, but Swift should then remind you that a "value of optional type 'URL?' [is] not unwrapped." Although you could use forced unwrapping to extract the value of the URL, I would recommend using optional binding instead:
if let url = URL(string: "https://api.io") {
Alamofire.request(
URL(string: "https://api.io"),
method: .post,
parameters: [
"grant_type": "client_credentials",
"client_id": "user00941",
"client_secret": "ILGddu8y8g7qW"
],
encoding: .urlEncodedInURL
).response {
request, response, data, error in
let json = JSON(data: data!)
print("OAuth 2 token obtained from API: \(json["access_token"])")
let token = "Bearer \(json["access_token"].stringValue)"
}
}
Alternatively, you could use a guard statement to preserve a Golden Path through your code:
guard let url = URL(string: "https://api.io") else {
return
}
This code has several errors. The encoding parameter needs to be set to JSONEncoding.default not .urlEncodedInURL.
In addition to this, the request, response, data, error in needs to be changed to response in. To get the data and error use response.data and response.error.

Yelp get request not working

When i do the same request in Postman everything is fine but when i try it in Alamofire i get an error.
I'm user Alamofire in swift for the request. Here is my code.
let parameters: Parameters = ["term": searchTerm as AnyObject, "location": "Washington DC" as AnyObject]
// let headers: HTTPHeaders = [tokenType!: accessToken!]
Alamofire.request("https://api.yelp.com/v3/businesses/search", method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: ["Authorization": "Bearer Access_token_************************"])
Error text:
{
error = {
code = "VALIDATION_ERROR";
description = "Please specify a location or a latitude and longitude";
};

Alamofire not sending the current headers (swift)

I keep getting "error_type":"OAuthException","code":"41" when I using alamofire or even when i made it through to the server I got data from before header's authorisation. I think it keep sending same header, how to make sure that alamofire send the current headers?
let headers = ["Authorization" : "\(AccessToken) \(TokenType)"]
print(headers)
Alamofire.request(.GET, "url/profile/", headers: headers, encoding: .JSON).responseJSON { response in
switch response.result {}
EDIT
First, I use login API
let parameters = [
"client_id": "\(Constant.clientId)",
"client_secret": "\(Constant.clientSecret)",
"response_type": "\(Constant.responseType)",
"scope" : "\(Constant.scope)",
"redirect_uri": "\(Constant.redirect)",
"email": "\(email!)",
"password": "\(pass!)"
]
print(parameters)
Alamofire.request(.POST, "http://url/login/", parameters: parameters, encoding: .JSON).responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
print("JSON: \(json)")
let accessToken = json["access_token"].string!
let refreshToken = json["refresh_token"].string
let tokenType = json["token_type"].string!
let expiresIn = json["expires_in"].string
}
And then, I use accessToken and tokenType for authorization
if(refreshToken != nil)
{
let headersCust = ["Authorization" : "\(accessToken) \(tokenType)"]
print(headersCust)
Alamofire.request(.GET, "http://goodies.co.id/api/v1/customer/profile/", headers: headersCust, encoding: .JSON).responseJSON { response in {}
Usually this problem is caused by Redirection. Using some networking debugging tool like Proxyman helps you to understand if this is a case; if so :
this is Alamofire 5(AF 5) solution:
let headers: [String:String] = [...]
let params: [String: Any] = [...]
let url = URL(...)
let redirector = Redirector(behavior: Redirector.Behavior.modify({ (task, urlRequest, resp) in
var urlRequest = urlRequest
headers.forEach { header in
urlRequest.addValue(header.value, forHTTPHeaderField: header.key)
}
return urlRequest
}))
//use desired request func of alamofire and your desired enconding
AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in
//handleDataResponse...
}.redirect(using: redirector)
I hope you are using the latest Alamofire so here is the code for .GET Request:
let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Content-Type": "application/x-www-form-urlencoded"
]
Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
.responseJSON { response in
debugPrint(response)
}
Reference: https://github.com/Alamofire/Alamofire
Try this out! And make sure you are sending the proper headers.

Resources