Swift Alamofire post "Extra argument in call" - swift

I want to post some xml to an url. This is my code:
func post(){
var data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Devices><Device><ID>EZR0114AF</ID><HEATAREA nr=\"4\"><T_TARGET>17.0</T_TARGET></HEATAREA></Device></Devices>"
Alamofire.request(urlPost, .post, parameters: data, encoding: .utf8, headers: nil).response { (response) in
print(response.data)
print(response.error)
print(response.response)
}
}
But I get a Syntax error: Extra argument in call. I have no idea what is missing, I tried a lot but nothing works. Any ideas?

Try changing the syntax to
let urlString = "XXXXXXXXX"
Alamofire.request(urlString, method: .post, parameters: ["id": "1,2,3,4"] ,encoding: JSONEncoding.default, headers: nil).responseString {
response in
switch response.result {
case .success(let responseString1):
print("the response is: \(responseString1)")
break
case .failure(let error):
print("The error is: \(error)")
}
}

Related

Swift - Alamofire returns "Invalid request format." when I try to upload file to pinata

print(element) print following
error = "Invalid request format."
Although the response.result is success.
I don't know what to do... appreciate any help.
let request = AF.request("https://api.pinata.cloud/pinning/pinFileToIPFS",
method: .post,
parameters: data,
encoding: JSONEncoding.default,
headers: [
"Content-Type": "multipart/form-data;boundary=nadeshiko_data_boundary",
"pinata_api_key": "myAPIKey",
"pinata_secret_api_key": "mySecretApiKey"
])
request.responseString { response in
print("responseString responseee", response)
switch response.result {
case .success(let element):
print(element)
case .failure(let error):
print("failure", error)
}
}
I asked to pinata support.
Turns out I was trying to upload JSON file where I have to upload a File.

Github API Error: Problems parsing JSON when following a user Swift 5

I am able to successfully login with github api on swift 5 with Alamofire but i have been struggling following a user for 2 days.
I am getting an error even though I have done every step in the Documentation
Here is my code:
func followUser(accessToken: String, completed: #escaping () -> ()){
let parameters = ["user": "follow"]
let headers : HTTPHeaders =
[
"Accept": "application/vnd.github.v3+json",
"Content-Length": "0",
"Content-Type": "application/json",
"Authorization" : "token \(accessToken)"
]
AF.request("https://api.github.com/user/following/jake", method: .put, parameters: parameters, headers: headers).responseData { response in
switch response.result {
case .failure(let error):
print(error)
case .success(let data):
let outputStr = String(data: data, encoding: String.Encoding.utf8) as String?
print("data \(outputStr!)")
DispatchQueue.main.async {
completed()
}
}
}.resume()
}
And i am getting this error:
{"message":"Problems parsing JSON",
"documentation_url":"https://docs.github.com/rest/reference/users#follow-a-user"}

Alamofire get method with parameters in the url with header swift

I have a get method with 3 parameters on the base url itself.I have tried the following code, but it is going to failure condition saying either not a valid url or not a valid JSON.
What is the correct way to approach this?
The code i have used is as below:
let header: HTTPHeaders = ["Content-Type":"application/json","x-token":self.token!]
let todosEndpoint: String = "https://reachwebdemo.com/2020/10/listcribdev/api/chatnotification?" + "channel_sid=\(self.channelsid!)&author=\(self.userid!)&message=\(inputMessage)"
if let encoded = todosEndpoint.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),let url = URL(string: encoded)
{
print("notify url is",url)
AF.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: header).responseString { response in
switch response.result {
case .success(let json):
print("Validation Successful for push notification",json)
case let .failure(error):
print("error for push notificaton",error.errorDescription)
}
}
}
You user parameters like url and it's wrong way to make request like this.
You need add parameters on request method like parameters. And yes, you can use parameters on 'GET' requests.
let header: HTTPHeaders = ["Content-Type":"application/json","x-token":self.token!]
let todosEndpoint: String = "https://reachwebdemo.com/2020/10/listcribdev/api/chatnotification"
let params:[String: Any] = ["channel_sid":self.channelsid!, "author":self.userid!, "message": inputMessage]
if let encoded = todosEndpoint.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
let url = URL(string: encoded) {
print("notify url is",url)
AF.request(url, method: .get, parameters: params, encoding: URLEncoding.default, headers: header).responseString { response in
switch response.result {
case .success(let json):
print("Validation Successful for push notification",json)
case let .failure(error):
print("error for push notificaton",error.errorDescription)
}
}
}

Swift Alamofire "The request timed out" in one of every two requests

In every one of my two calls to loadHeader with the same URL, I get "The request timed out" error. In first try, the function works and I manage to get and parse the response. In second, I get time out. In third it works and in forth time out again. Is it about my code or about server? I tried waiting before trying again as it might be some security protocol of server but it didn't change anything.
Here is error code:
FAILURE: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."
And here is my code:
func loadHeader(url: String){
let parameters = ["foo": "bar"]
Alamofire.request(url, method: .get, parameters: parameters, encoding: JSONEncoding.default)
.validate { request, response, data in
// Custom evaluation closure now includes data (allows you to parse data to dig out error messages if necessary)
return .success
}
.responseJSON {
response in
let json=response.data
self.jsonToObjectHeader(json: json!)
}
}
func jsonToObjectHeader(json:Data){
do{
databases = try JSONDecoder().decode(responseHeader.self,from: json)
if databases.ordersHeader.count == 0 {
let alert = UIAlertView(title: "empty",message: "empty",delegate: nil,cancelButtonTitle: "OK")
alert.show()
}
else {
for i in 0...databases.ordersHeader.count-1 {
myArray2.append(databases.ordersHeader[i].productName!)
}
}
DispatchQueue.main.async {
self.myTableView.reloadData()
self.myTableView.tableFooterView = UIView()
}
//print(databases.ordersHeader[0].companyAddress)
}catch let jsonErr {
print(jsonErr)
}
}
I've added
let parameters = ["foo": "bar"]
thinking I've to give parameters as it is in the function. Just updated
Alamofire.request(url, method: .get, parameters: parameters, encoding: JSONEncoding.default)
to
Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default)
and it solved the issue. Posting this in case of someone experiences something similar.

Getting the returned error message from Alamofire

I am struggling to get the json error message returned using Alamofire and their .success / .failure method.
Before using this I could use response.result.value and get the returned error message but now I am validating the status code .validate(statusCode: 200..<300).
Have tried several things to receive the error but it always produces nil or just the status code.
Alamofire.request(url, method: .post, parameters: body, encoding: JSONEncoding.default)
.validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result {
case .success:
//Other stuff
case .failure(let error):
print(response.result.value) //Produces nil when there is an error
print(error.localizedDescription)
print(response.result.error.customMirror)
print(response.result.error.debugDescription)
print(response.result.error.unsafelyUnwrapped)
print(response.result.error?.localizedDescription)
}
}
How can I get the error json? It is getting returned as such.
{
"status": "error",
"message": "Incorrect Password"
}
take that .validate() out. You will see more detailed description.