My mates and I are working on a iOS Project, and we get stacked in this issue.
We are trying to make a POST request to our API, but all we are getting is a success code but with a reponse of type:
SUCCESS: { detail = "Authentication credentials were not provided."; }
This is our code:
#IBAction func accept(_ sender: Any) {
var comm,cat,dist : String!
comm = observationstwee.text!
print(comm)
let catd = 7
cat = String(catd)
print(cat)
dist = distancetwee.text!
print(dist)
let parameters: Parameters = [
"comment":comm,
"category":cat,
"distance":dist,
"timestamp":time
]
let headers: HTTPHeaders = ["Authorization": "Token \(token!)"]
print(headers.debugDescription)
Alamofire.request("https://llegoelbigotes.ubiqme.es/api/new-travel",parameters: parameters, headers: headers).responseJSON {response in switch(response.result) {
case .success(_):
print(response)
print("Correct Travel")
//changeViewController(storyboard_name: "Main", viewcontroller_name: "tabBarController", context: self)
break
case .failure(_):
print("FAILURE")
}
}
}
As well as with this call:
Alamofire.request("https://llegoelbigotes.ubiqme.es/api/new-travel",method:.post,parameters: parameters,headers:headers, encoding: JSONEncoding.default).validate().responseJSON
We get this:
"Extra argument 'method' in call"
Thank you so much for your help, we are working with Alamofire 4.5 and iOS 11.2
This type of error occurs when one of the parameters it’s not correct, in your example this is probably the “headers” parameter, try:
let headers = ["Authorization": "Token \(token!)"]
And check the Alamofire migration guide, you could use the RequestAdapter protocol.
when you are using post method so you need to provide the method type to the request argument code should be like that
request("https://llegoelbigotes.ubiqme.es/api/new-travel", method:
.post, parameters: parameters, encoding: JSONEncoding.default, headers:
headers).responseJSON(completionHandler:{ responseObject in
})
Related
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:
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: [:])
I'm trying to read the JSON using Alamofire. Here is my code:
let headers = ["Content-Type": "application/json"]
func getConfirmationCode(params: [String:Any], block: #escaping(_ data : JSON, _ success : Bool) -> Void) {
if let url = URL(string: baseURL + "getConfirmationCode.php") {
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
DispatchQueue.main.async {
if let value = response.result.value {
let json = JSON(value)
block(json, true)
} else {
block(JSON.null, false)
}
}
}
}
}
The JSON is valid, everything works perfectly in Postman, but I can't make it work. None of the suggestions on the web helped (changing the responseJSON to responseString/responseData, changing the JSONEncoding.default to URLEncoding.default, etc.)
Can anyone help me?
You should try to check response in postman in "Preview" tab of response section. sometime it displays proper json in "Pretty" section. but in "Preview" section it many contains some print statements of API response. and those print statements makes problem in json decoding.
also, if you want to get swift code of postman response you can always get it from postman's code feature:
Hope this helps..!
I am afraid I cannot share the API url. But I have checked on Postman, it works. It is a POST request and following is the response :
{
"user_key": "b0aebdedb15e2beaaf479ca3c4f8227e8e970681"
}
Postman screenshot :
In code, this is the request I am making using Alamofire :
Alamofire.request("some url", method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: ["Content-Type":"application/json"])
.responseObject { (response: DataResponse<User>) in
let userResponse = response.result.value
print("")
}
But userResponse comes to be nil. This is the User object :
import ObjectMapper
class User: Mappable {
var authToken: String?
required init?(map: Map) {
}
func mapping(map: Map) {
self.authToken <- map["user_key"]
}
}
I am using ObjectMapper here.
Assuming the it is not a JSON object, I tried to handle it as a String :
Alamofire.request("some url", method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: ["Content-Type":"application/json"])
.responseString { (response: DataResponse<String>) in
let dataUser = response.data as! Any
let dataUser1 = response.data as! AnyObject
let error = response.error
let code = response.response?.statusCode
print(response.value)
print(response.result.value)
}
Still, nothing. I am not able to retrieve the value. The status code however comes out to be 400 (bad request).
What exactly is it ? JSON object or String ? How do I fix this ?
Just try to replace
this URLEncoding.httpBody to JSONEncoding.default
JSONEncoding.default
Uses JSONSerialization to create a JSON representation of the parameters object, which is set as the body of the request. The Content-Type HTTP header field of an encoded request is set to application/json.
Alamofire reference
I am trying to send a post request as follows, My Router as follows
enum ProfieRouter: URLRequestConvertible {
case loginUser(parameters: Parameters)
case resetPassword(parametrs: Parameters)
var method: HTTPMethod {
switch self {
case .loginUser:
return .post
case .resetPassword:
return .post
}
}
var path: String {
switch self {
case .loginUser:
return "app/api.php?request=login"
case .resetPassword:
return "app/api.php?request=forgettenPassword"
}
}
func asURLRequest() throws -> URLRequest {
let BASEURL = "https://www.example.com/"
let url = try BASEURL.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
switch self {
case .loginUser(let parameters):
urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
case .resetPassword(let parameters):
urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
}
return urlRequest
}
}
This is how i call it from ViewController,
#IBAction func signInButtonClicked(_ sender: Any) {
let parameters: Parameters = [
"email": "xxxxxx",
"password": "xxxxxx"
]
Alamofire.request(ProfieRouter.loginUser(parameters: parameters)).responseJSON{ response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
}
But i got following error as follows,
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
Please note that, my API response is a valid when i checked with POSTMAN and Advanced REst Client. And i have tried several question regarding following error but non of them work in my case.
Please can someone point out the mistake i have done here.
Thank you.
Try this..
Modify you web-service calling code like this :
// Add default headers if needed.(As per your web-service requirement)
let headers: HTTPHeaders = [
"Accept": "text/html",
"Content-Type" : "application/x-www-form-urlencoded"
]
Alamofire.request("Your URL", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).validate().responseJSON { (response) in
debugPrint(response)
}
Hope it helps.