Search code examples
iosswiftalamofire

Extra argument in .request call -- Alamofire + Swift


I'm trying to make a .request() call using Alamofire 4 and Swift 4. Here's the code I'm using:

static func getPlaceData(url: String, parameters: [String: String]) {
    Alamofire.request(url, method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
        if response.result.isSuccess {
            let json: JSON = JSON(response.result.value!)
            print(json)
        } else {
            print("error")
        }
    }
}

where headers is:

let headers: HTTPHeaders = [
        "Authorization": "Bearer /*PRIVATE KEY*/"
]

I am getting the following error: Extra argument 'method' in call, at the Alamofire.request(... line.

I've read through quite a few SO posts about similar issues but none of their solutions have fixed my problem:

I've also read in the this documentation guide and this issues thread on GitHub but neither have solved the issue.

What is the proper syntax for a .request() call with required parameters and headers?

The code is for making an authenticated call from Swift code using the Yelp Fusion API -- maybe someone can suggest a better method than Alamofire?


Solution

  • I figured out the issue, no thanks to any documentation or GitHub threads.

    The logic in the above code snippet (from the question) referenced a constant called headers, which was declared outside of getPlaceData(url:parameters:). This is because in order to access the Yelp Fusion API you need to include an extra field in the HTTP header you send to include the private API key using the format mentioned here.

    I moved the headers data structure inside of getPlaceData(url:parameters:) and it fixed the issue, so my resulting function is as follows:

    static func getPlaceData(url: String, parameters: [String: String]) {
      let headers: HTTPHeaders = [
        "Authorization": "Bearer /*PRIVATE KEY*/"
      ]
    
      Alamofire.request(url, method: .get, parameters: parameters, encoding: 
      JSONEncoding.default, headers: headers).responseJSON { (response) in
        if response.result.isSuccess {
          let json: JSON = JSON(response.result.value!)
          print(json)
        } else {
          print("error")
        }
      }
    }
    

    Not sure why this fixed the issue, but the code works now.