54

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 ?

Matt Hampel
  • 5,088
  • 12
  • 52
  • 78
Agreensh
  • 1,305
  • 1
  • 12
  • 15

14 Answers14

78

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!

Abdullah Md. Zubair
  • 3,312
  • 2
  • 30
  • 39
  • 8
    Is it working? I am still getting the error of extra parameter in call while using this also `Alamofire.request(url, method: .post, parameters: nil, headers: nil, encoding: JSONEncoding.default)` – Rajan Maheshwari Sep 15 '16 at 13:21
  • Do you mean `Alamofire.request(url!, method: .post, parameters: parameters, encoding: nil, headers: nil)` or this `Alamofire.request(url!, method: .post, parameters: parameters, headers: nil)` there are still errors. Even this line shows the same error `Alamofire.request(url!, method: .post, parameters: nil, headers: nil, encoding: JSONEncoding.default)` – Rajan Maheshwari Sep 15 '16 at 13:28
  • are you using Alamofire version 4.0.0 & can you remove optional sign (!) from url ? – Abdullah Md. Zubair Sep 15 '16 at 13:31
  • Alamofire is the latest one i.e 4.0.0 and optional has nothing to do with extra parameter. As URL returns an optional, so we have to unwrap it. Are you sure the line written by you in answer `Alamofire.request(patientIdUrl, method: .post, parameters: nil, headers: nil, encoding: JSONEncoding.default)` is working? – Rajan Maheshwari Sep 15 '16 at 13:33
  • works for me without encoding param, I am using as followings: `Alamofire.request(url, method: .post, parameters: dict, headers: header)` – Abdullah Md. Zubair Sep 15 '16 at 13:35
  • Well this worked `Alamofire.request("http//yourserviceURL.com", method: .post, parameters: parameters, headers: nil).responseJSON { (response:DataResponse) in switch(response.result) { case .success(_): if let data = response.result.value{ print(response.result.value) } break case .failure(_): print(response.result.error) break } }` – Rajan Maheshwari Sep 15 '16 at 13:41
  • No need to remove the encoding parameter. Check my answer – Rajan Maheshwari Sep 15 '16 at 15:11
  • 1
    @Abdullah Md.Zubair,@Rajan Maheshwari i tried with your above answers still am getting extra arguement in call issue my code is func POST(url _url: String, params: [String : AnyObject]) -> Future {let request = Alamofire.request(.POST, self.buildAppUrl, method: .post, parameters: params, encoding: JSONEncoding.JSON, headers: self.requestHeaders())}.Thanks – Vinathy nvr Jan 04 '17 at 08:28
  • @Vinathynvr try as followings: Alamofire.request(self.buildAppUrl, method: .post, parameters: params, encoding: JSONEncoding.default, headers: self.requestHeaders()) .responseJSON { response in } – Abdullah Md. Zubair Jan 04 '17 at 09:22
  • @AbdullahMd.Zubair now am getting extra argument method in call error. – Vinathy nvr Jan 04 '17 at 09:27
  • 1
    Alamofire.request("", method: .post, parameters: [:], encoding: JSONEncoding.default, headers: [:]) .responseJSON { response in } this works on my side, make sure you are getting proper values from your methods like self.buildAppUrl, params & self.requestHeaders() – Abdullah Md. Zubair Jan 04 '17 at 09:35
  • url must be of type `String`. – Allan Macatingrao Dec 10 '18 at 07:24
72

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

Rajan Maheshwari
  • 14,465
  • 6
  • 64
  • 98
  • @jimijon Its the same as post. Check my updated answer and try any get URL. Leave the parameters blank as `["":""]` – Rajan Maheshwari Sep 19 '16 at 16:17
  • Ok, just a "red herring" in the error. If any of the other parameters, headers et are wrong, then it gives this weird error. – jimijon Sep 19 '16 at 20:16
  • Haven't tried with wrong headers. Will give a try and let you know – Rajan Maheshwari Sep 20 '16 at 02:59
  • Please, can you add a link to Alamofire documentation in which you have see that? I could only find this: https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md#json-encoding that always say: `Extra argument in call` – Francisco Romero Sep 23 '16 at 07:04
  • @Error404 Read the section `Parameter Encoding Protocol` in the documentation where they have stated everything and the type of parameters should be `[String:Any]`. My error of extra argument call was because of parameter passed as `AnyObject`. https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md#parameter-encoding-protocol – Rajan Maheshwari Sep 23 '16 at 16:01
  • Yes, I have read the section that you linked before but I cannot find where all kind of parameters I can choose. For example, method, encoding as you used in your function. – Francisco Romero Sep 23 '16 at 21:21
  • 2
    @Error404 Encoding depends on the type of API is made at server end. If it accepts post parametes not as raw form, then you have to use `URLEncoding.default`. If it accepts post parameters as raw form, then you have to choose `JSONEncoding.default` In `GET` you don't need any of them. If it accepts paramters as form data multipart form, then you have to use the `multipart` feature of alamofire – Rajan Maheshwari Sep 24 '16 at 05:23
  • Thank you for the explanation! :) I could not find that info before – Francisco Romero Sep 25 '16 at 18:41
  • The order of parameters is important. it must be: method, parameters, encoding, headers. – ricardokrieg Oct 19 '16 at 02:15
  • @ricardokrieg What are you talking about? Did you see anything wrong here? – Rajan Maheshwari Oct 19 '16 at 04:28
  • 1
    @RajanMaheshwari sorry, I meant the order of arguments (for Alamofire.request call). It must be exactly like you did. – ricardokrieg Oct 19 '16 at 19:07
  • @ricardokrieg ok, thanks for the appreciation. Can I get a +1 for that :) – Rajan Maheshwari Oct 19 '16 at 20:30
  • @RajanMaheshwari I'm using the latest swift and alamofire, if you get a chance could you take a look at : http://stackoverflow.com/questions/41484477/nsmutableurlrequest-in-router-class-swift-3 – user2363025 Jan 05 '17 at 12:47
  • This answer explains it perfectly. Also, the order in which the parameters are to be listed under the Alamofire.request method is very crucial. For example (URL,methods,parameters,encoding,headers). Any change in this order will lead to an error. – SeaWarrior404 Jul 16 '17 at 09:22
  • 1
    You are right,headers should be [String:String].Thanks for your help. – 无夜之星辰 Aug 07 '17 at 08:39
5

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 
                        }
                 }
Raksha Saini
  • 604
  • 12
  • 28
4

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

xevser
  • 369
  • 4
  • 5
2

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)")

        }

    }
oskarko
  • 3,382
  • 1
  • 26
  • 26
1

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.

Chi Minh Trinh
  • 296
  • 4
  • 11
1

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!

onlinebaba
  • 81
  • 1
  • 2
1
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!)
    }
}
סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68
0

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.

Narasimha Nallamsetty
  • 1,215
  • 14
  • 16
0

I fixed this issue with:

  1. Reorder parameters (url then method type).
  2. Change Encoding Enum to be "JSONEncoding.default" for example.

Note that: Alamofire methods signature change in Swift 3

Ahmed Lotfy
  • 3,806
  • 26
  • 28
0

Two things that I found worth noting.

  1. 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,.
  2. Make sure the data type of the parameters is [String: String]. Declare it explicitly.
Jiang Xiang
  • 3,166
  • 5
  • 21
  • 31
0

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)
0

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)
Pang
  • 9,564
  • 146
  • 81
  • 122
0

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
            }
    }
Pritesh
  • 980
  • 7
  • 17