swift 3.0: Extra argument in call [duplicate] - post

I have migrated my project to Swift 3 (and updated Alamofire to latest Swift 3 version with pod 'Alamofire', '~> 4.0' in the Podfile).
I now get an "Extra argument in call" error on every Alamofire.request. Eg:
let patientIdUrl = baseUrl + nextPatientIdUrl
Alamofire.request(.POST, patientIdUrl, parameters: nil, headers: nil, encoding: .JSON)
Can anybody tell me why ?

According to Alamofire documentation for version 4.0.0 URL request with HTTP method would be followings:
Alamofire.request("https://httpbin.org/get") // method defaults to `.get`
Alamofire.request("https://httpbin.org/post", method: .post)
Alamofire.request("https://httpbin.org/put", method: .put)
Alamofire.request("https://httpbin.org/delete", method: .delete)
So your url request will be:
Alamofire.request(patientIdUrl, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: nil)
and a sample request will be:
Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: [AUTH_TOKEN_KEY : AUTH_TOKEN])
.responseJSON { response in
print(response.request as Any) // original URL request
print(response.response as Any) // URL response
print(response.result.value as Any) // result of response serialization
}
Hope this helps!

This one worked for me. No need to remove encoding parameter
Update for Swift 5.x
Alamofire uses the Result type introduced in Swift 5.Also Alamofire.request has been changed to AF.request which will now read their switch response.result value with .success and .failure
AF.request("https://yourServiceURL.com", method: .get, parameters: [:], encoding: URLEncoding.default, headers: ["":""]).responseJSON { (response) in
switch response.result {
case let .success(value):
print(value)
case let .failure(error):
print(error)
}
}
Swift 3.x / 4.x
Alamofire.request("https://yourServiceURL.com", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if let data = response.result.value{
print(response.result.value)
}
break
case .failure(_):
print(response.result.error)
break
}
}
and make sure that the parameters are of type
[String:Any]?
In case of Get
Alamofire.request("https://yourGetURL.com", method: .get, parameters: ["":""], encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if let data = response.result.value{
print(response.result.value)
}
break
case .failure(_):
print(response.result.error)
break
}
}
Even works with
JSONEncoding.default
For Headers
If you are passing headers, make sure their type should be [String:String]
Go through the Parameter Encoding Link
https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md#parameter-encoding-protocol

Post method Alamofire 4.0 with Swift 3.0 and xCode 8.0
Alamofire.request(URL, method: .post, parameters: PARAMS)
.responseJSON { closureResponse in
if String(describing: closureResponse.result) == "SUCCESS"
{
// Sucess code
}
else
{
// Failure Code
}
}

My solution is if you are using headers, its type must be [String:String].

This error is up to parameters value. It has to be [String: String]
let url = URL(string: "http://yourURLhere")!
let params: [String: String] = ["name": "oskarko", "email": "youremail#here.com", "sex": "male"]
Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).validate(statusCode: 200..<600).responseJSON() { response in
switch response.result {
case .success:
var result = [String:String]()
if let value = response.result.value {
let json = JSON(value)
}
case .failure(let error):
print("RESPONSE ERROR: \(error)")
}
}

I just resolved the same problem as you have. The problem is I have imported Alamofire in the header, so I just remove the Alamofire when call request. Like that:
request(.POST, patientIdUrl, parameters: nil, headers: nil, encoding:
.JSON)
I hope it can help you.

I ran into this same Extra argument 'method' in call error when my URL variable was out of scope.
In your case, please make sure both baseUrl and nextPatientIdUrl are in scope when they are being used Alamofire.request(patientIdUrl,..) method.
Hopefully this resolves your issue. Thanks You!

func API()
{
if Reachability.isConnectedToNetwork()
{
let headers = ["Vauthtoken":"Bearer \(apiToken)"]
print(headers)
// let parameter = ["iLimit":"10","iOffset":"0","iThreadId":"1"]
ApiUtillity.sharedInstance.showSVProgressHUD(text: "Loding...")
Alamofire.request(ApiUtillity.sharedInstance.API(Join: "vehicle/CurrentVehicleLists"), method:.get, parameters:nil, headers: headers).responseJSON { response in
switch response.result {
case .success:
print(response)
ApiUtillity.sharedInstance.dismissSVProgressHUD()
let dictVal = response.result.value
let dictMain:NSDictionary = dictVal as! NSDictionary
let statusCode = dictMain.value(forKey: "status") as! Int
if(statusCode == 200)
{
}
else if statusCode == 401
{
}
else
{
}
case .failure(let error):
print(error)
ApiUtillity.sharedInstance.dismissSVProgressHUD()
}
}
} else
{
ApiUtillity.sharedInstance.dismissSVProgressHUD()
ApiUtillity.sharedInstance.showErrorMessage(Title: "Internet Connection", SubTitle: "Internet connection Faild", ForNavigation: self.navigationController!)
}
}

For me this is working.
For GET Request
Alamofire.request("http://jsonplaceholder.typicode.com/todos/1/get").responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil{
print(response.result.value!)
}
break
case .failure(_):
print(response.result.error)
break
}
}
For POST
let parameters = NSDictionary(object: "nara", forKey: "simha" as NSCopying)
Alamofire.request("http://jsonplaceholder.typicode.com/posts", method: HTTPMethod.post, parameters: parameters as? Parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil{
print(response.result.value!)
}
break
case .failure(_):
print(response.result.error)
break
}
}
Thanks #Rajan Maheswari.

I fixed this issue with:
Reorder parameters (url then method type).
Change Encoding Enum to be "JSONEncoding.default" for example.
Note that: Alamofire methods signature change in Swift 3

Two things that I found worth noting.
Remove the first url label before its value. Use
Alamofire.request("https://yourServiceURL.com", method: .post,
instead of Alamofire.request(url: "https://yourServiceURL.com",
method: .post,.
Make sure the data type of the parameters is [String:
String]. Declare it explicitly.

I copy this code from Alamofire,create a URLRequest and used Alamofire.request(URLRequest) method, avoid this error
originalRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters)

I fixed this issue this way:
Just remove extra parameters, just parameters, encoding and headers, if these parameters are nil you can remove then and leave this way,
Alamofire.request(yourURLString, method: .post)

If you have added Alamofire files locally then don't use "Alamofire" before request
let apipath = “your api URL”
request(apipath, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { response in switch(response.result) {
case .success(_):
do {
let JSON = try JSONSerialization.jsonObject(with: response.data! as Data, options:JSONSerialization.ReadingOptions(rawValue: 0))
guard let JSONDictionary: NSDictionary = JSON as? NSDictionary else {
print("Not a Dictionary")
return
}
print("Post Response : \(JSONDictionary)")
}
catch let JSONError as NSError {
print("\(JSONError)")
}
break
case .failure(_):
print("failure Http: \(String(describing: response.result.error?.localizedDescription))")
break
}
}

Related

Alamofire Value of type 'Result<Any, AFError>' has no member 'isSuccess' (Swift 5)

I have a simple procedure, which I used in my earlier version (Swift 4). I have now updated to the new version (Swift 5, Alamofire 5.0.0-rc.2), as I am still beginner I got problems with this. Some code parts I could already rewrite.
let headers: HTTPHeaders = [
"SubscriptionKey": SubscriptionKey,
"Host": HostName
]
AF.request(URL(string: userInfoUrl)!, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers)
.validate()
.responseJSON { response in
guard response.result.isSuccess else {
log.error("Error requesting user ID: \(String(describing: response.result.error))")
completion(false, nil)
return
}
guard let json = response.result.value as? [String: Any], let userId = json["userId"] as? String else {
log.error("Malformed result from API call.")
completion(false, nil)
return
}
response.result.isSuccess is not possible. How can I reuse this part?
Error: Value of type 'Result' has no member 'isSuccess'
As a possible solution, I will test the above solution.
AF.request(URL(string: userInfoUrl)!, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers)
.validate()
.responseJSON { response in
switch response.result{
case .success(let value):
//succcess, do anything
case .failure(let error):
log.error("Error requesting user ID: \(String(describing: response.error))")
completion(false, nil)
return
}
Result is containing .success or .failure case.
So you should treat isSuccess like this
switch response.result {
case .success(let value):
//success, do anything
case .failure(let error):
//failure
}

get Data from alamofire (responseString)

I am retrieving the data with this code
Alamofire.request(urlString, method: .post, parameters: parameters,encoding: JSONEncoding.default, headers: headers)
.responseString() { response in
switch response.result {
case .success(let data):
let jsonData = JSON(data)
print(jsonData)
case .failure(let error):
print("\(error) - hello world")
}
}
and the result that has sent by the server is
{"result":"Opertion is successfull"}
but i just want the value part "Opertion is successfull"
Use the code from the almofire documentation
Alamofire.request(urlString, method: .post, parameters: parameters,encoding: JSONEncoding.default, headers: headers)
.responseString() { response in
if let jsonData = response.result.value {
print("JSON: \(jsonData)") // serialized json response
}
}

How to post parameters to the server using Alamofire?

I don't know if I am posting the parameters correctly?
func removeCart(rowId: Int, completion: #escaping (Bool)->()) {
let urlString = "\(BaseUrl.Protina.rawValue)/ApiShoppingCart/UpdateCart"
let headers: HTTPHeaders = ["Content-Type": "application/form-data"]
let parameters : [String: Any] = ["removefromcart": rowId]
Alamofire.request(urlString, method: .post, parameters: parameters,encoding: JSONEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success(let data):
let jsonData = JSON(data)
print(jsonData)
completion(true)
case .failure(let error):
print(error)
}
}
}
when a user tries to remove an item from the cart, the above function gets fired
and after item deleted the rest of the items from cart will return.
Also, I tested it with postman and it was successful.
I found the answer, the problem was in the parameter and encoding.
Changed it to this:
let parameters: [String:Any]= [
"removefromcart": rowId,
"Content-Type" : "application/form-data"
]
And the encoding should be URLEncoding.httpBody

How to send request in Alamofire 4.0 only with parameters and Body using POST method in swift?

I am using like this, but in this case, I need to call API with parameters and Body. Please help me. Thanks in advance.
Alamofire.request(postUrl, method: .post, parameters: params, encoding: CustomPostEncoding(), headers: nil).validate().responseJSON{ response in
switch response.result
{
case .success:
MBProgressHUD.hide(for: self.view, animated: true)
if let val = response.result.value
{
let json = JSON(val)
print(json)
}
case .failure(let error):
print(error)
}
}
var url = "http://..."
let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
let params : Parameters = ["grant_type":"password","username":"mail","password":"pass"]
let url = NSURL(string:"url" as String)
request(url, method: .post, parameters: params, encoding: URLEncoding.httpBody , headers: _headers).responseJSON(completionHandler: {
response in response
let jsonResponse = response.result.value as! NSDictionary
if jsonResponse["access_token"] != nil
{
access_token = String(describing: jsonResponse["accesstoken"]!)
}
})
Refrence :- POST request with a simple string in body with Alamofire
use your parameters instead of class_id ,and time.
func listOfClassesData(url: String,class_id: String,time: String,redClassesData : [String: Any] ,completionHandler:#escaping (Bool) -> ()){
let Auth_header = ["Authorization" : "Bearer "+getBearerToken()]
let paameters:Parameters = [
"class_id" : class_id,
"time" :time,
]
print(url,Auth_header)
Alamofire.request(url, method: .post, parameters: paameters, encoding: JSONEncoding.default, headers: Auth_header)
.responseJSON { response in
print(response)
switch response.result{
case .success:
let statusCode: Int = (response.response?.statusCode)!
switch statusCode{
case 200:
if let json = response.result.value{
completionHandler(true)
}
break
default:
completionHandler(false)
break
}
break
case .failure:
completionHandler(false)
break
}
}
}
let url = "your api url"
let param = ["user":"user#test.com","pass":"12345"]
Alamofire.request(url, method: .post , parameters: param)
.validate()
.responseJSON {
response in
switch response.result{
case .success:
var jsonResult = [String:AnyObject]()
do
{
//Get response successfully of api
jsonResult = try JSONSerialization.jsonObject(with: response.data!, options: []) as! [String:AnyObject]
print(jsonResult)
}
catch let error as NSError {
//get error if there is any problem in response of api.
print("--->",error)
}
case .failure(let error):
//get error if there is any problem while calling api.
print("---->",error)
}
}

Alamofire Parameter missing in response

I install pod file of Alamofire for calling web service and successfully retrieve data when there is no parameter pass to web service but when I try to pass parameter It shows this parameter missing.
Here is my code:
let parameters: Parameters = ["client_id": "1","user_token":"A4YkkH5FdTbRCI8Mk98s"]
let url = "http://***********/index.php/Web_api/get_client_profile"
Alamofire.request(url , method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil{
print(response.result.value)
}
break
case .failure(_):
print(response.result.error)
break
}
}
RESPONSE:
{
"message : client_id parameter missing",
"Code : 500"
}
What I am doing wrong ? Please help me with it.
Thank you
After banging my head for like 6 Hours I figured a different approach, here is a way of calling it, which works:
var request: Alamofire.Request? {
didSet {
oldValue?.cancel()
}
}
func loadDataFromServer(message:String?) {
// Prerequisites for Connection to Server
let timeParameter = self.getLastTimeStamp()
let url = "http://your.amazing.url/path/component/classs"
let parameter = ["timestamp":timeParameter]
//sho hud only of there is no data listed
if message != nil {
HUD.show(HUDContentType.label("Loading.."))
}
self.request = Alamofire.request(url, method: .post, parameters:parameter)
if let request = request as? DataRequest {
request.responseString { response in
PKHUD.sharedHUD.hide()
do{
let dictionary = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
//Save and Fetch
self.saveTimestamp(dictionary: dictionary, wsEntity: "Section")
self.saveDataInPersisanceStorage(articalDictionary: dictionary)
self.fetchDatafromCore()
//HUD.flash(.success, delay:1.0)
}catch{
//HUD.flash(.error, delay:1.0)
}
}
}
}

Resources