Alamofire, Extra argument 'method' in call [duplicate] - alamofire

This question already has answers here:
Swift 3.0, Alamofire 4.0 Extra argument 'method' in call
(5 answers)
Closed 3 years ago.
I have google some answers with no luck, I got this error "Extra argument 'method' in call" and is pointing at the ".get", but if i remove the "headers : headers as? [String: Any]" it works. Please help
let urlParams:[String : Any] = [
"target": target,
"q": textToTranslate,
"key": GOOGLE_CLOUD_API_KEY,
"source": source]
let headers:[String : Any] = ["Content-Type": "application/json",
"X-Ios-Bundle-Identifier": Bundle.main.bundleIdentifier as Any]
// Fetch Request
let urlString = TRANSLATE_API
Alamofire.request(urlString, method : .get, parameters : urlParams as? [String: Any], encoding : JSONEncoding.default , headers : headers as? [String: Any]).responseJSON(completionHandler: { (response:DataResponse<Any>) in
})

I changed header:[String : Any] to header:[String : String]
let bundleIdentifier = Bundle.main.bundleIdentifier!
let headers:[String : String] = ["Content-Type": "application/json", "X-Ios-Bundle-Identifier": bundleIdentifier]

Related

How convert URL building code from Objective-C to Swift? [duplicate]

This question already has answers here:
Swift - encode URL
(19 answers)
Closed 3 years ago.
I have Objective-C code to build a URL. How to write in Swift 3 code?
NSString *urlString = [[NSString alloc]initWithFormat:#"http://smartbaba.in/Familynk/api/registration.php?phone_no=%#&email=%#&password=%#&first_name=%#&last_name=%#",txtmobileno.text,txtemail.text,txtpassword.text,txtfirstname.text,txtlastname.text];
Try This
"http://smartbaba.in/Familynk/api/registration.php?phone_no=\(txtmobileno.text)&email=\(txtemail.text)&password=\(txtpassword.text)&first_name=\(txtfirstname.text)&last_name=\(txtlastname.text)"
Swift conversion can be something like this
// I thing code requires no explanation, its self explanatory
func makeUrl(phoneNo: String, email: String, password: String, firstName: String, lastName: String) {
// first way but not recomended
let urlString = "http://smartbaba.in/Familynk/api/registration.php?phone_no=\(phoneNo)&email=\(email)&password=\(password)&first_name=\(firstName)&last_name=\(lastName)"
print("\(urlString)")
// second way, ASAIK this is good way for constructing URL's
var components = URLComponents()
components.scheme = "http"
components.host = "smartbaba.in"
components.path = "/Familynk/api/registration.php"
components.queryItems = [
URLQueryItem(name: "phone_no", value: phoneNo),
URLQueryItem(name: "email", value: email),
URLQueryItem(name: "password", value: password),
URLQueryItem(name: "first_name", value: firstName),
URLQueryItem(name: "last_name", value: lastName)
]
let url = components.url
print(url) // returns URL
print(url?.absoluteString) // returns url path in string
}
// call function
makeUrl(phoneNo: "12345", email: "test#gmail.com", password: "12345678", firstName: "test", lastName: "user")
You can simply use String interpolation to create a String with multiple parameters like,
let urlString = "http://smartbaba.in/Familynk/api/registration.php?phone_no=\(txtmobileno.text)&email=\(txtemail.text)&password=\(txtpassword.text)&first_name=\(txtfirstname.text)&last_name=\(txtlastname.text)"
Now, to get the URL using urlString,
if let url = URL(string: urlString) {
//use url here...
}
post method using URLSession:
let myUrl = URL(string: "http://smartbaba.in/Familynk/api/registration.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
let postString = "firstName=James&lastName=Bond";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
print(parseJSON)
}
} catch {
print(error)
}
}
task.resume()
If you are using Alamofire then,
let parameters: Parameters = [
"Subject": "hallo"
]
let url = "http://mydomain/mydb/mydb_tesT.NSF/api/data/documents/unid/DD026770D91AA23DC1257EF90035E1C4"
Alamofire.request(url, method:.post, parameters:parameters, headers:headers).responseJSON { response in
switch response.result {
case .success:
debugPrint(response)
case .failure(let error):
print(error)
}
}

Swift 4.2 Alamofire : Extra argument 'method' in call

I have updated my codes to Xcode 10 and Swift 4.2 , i have got this error. extra arguments.
I tried all solutions available but they are perhaps for older versions of swift. I am usign alamofire version :Alamofire 4.7.3
and here is my code :
func callRemoveUserApi() {
let token = SharedManager.getAuthenticationToken()
MBProgressHUD.showAdded(to: self.view, animated: true)
let headers = [
"token": token
]
let manager = SharedManager.sharedInstance
let user = manager.getUpCurrentUser()
var params = [String:String]()
params = [
"id": user.removed_member!.description,
"userpath":self.selectedUser.userpath!,
"path":user.path!
]
Alamofire.request(removeMember, method:.put, parameters: params, encoding: JSONEncoder.default, headers: headers).responseJSON { response in
print("Request \(String(describing: response.request))")
print("RESPONSE \(String(describing: response.result.value))")
print("RESPONSE \(response.result)")
print("RESPONSE \(response)")
switch response.result {
case .success:
MBProgressHUD.hide(for: self.view, animated: true)
var tempResponseDict = response.result.value as! NSDictionary
// var array = tempResponseDict.object(forKey: "data") as! NSArray
NotificationCenter.default.post(name: Notification.Name("callMatchesApi"), object: nil)
self.navigationController?.popViewController(animated: true)
break
case .failure( _):
MBProgressHUD.hide(for: self.view, animated: true)
break
}
}
}
Solution :
convert JSONEncoder.default to JSONEncoding.default
and Alamofire call will be.
Alamofire.request(mobileInfo, method:.put, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
Header Declaration :
var header : [String:String]?
Adding values to Header :
header = [AppConstant.Content:AppConstant.ContentType,
AppConstant.Authorization : UserDefaults.standard.secretObject(forKey: AppConstant.AuthToken) as! String]
Alamofire method :
Alamofire.request(mobileInfo, method:.put, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
Hope this will work for you, Good Luck.. :)

Swift 3.0 notification transformable to array or array of dictionaries?

Getting this data back as a notification and want to read it into usable variable types. I got all of them to work but the rewards and aps
%# [AnyHashable("description"): Open 10 common chests., AnyHashable("icon"): localhost:8000//media/achievements/Common%20Chest%20Go- Getter/bomb.jpg, AnyHashable("name"): Common Chest Go-Getter, AnyHashable("gcm.message_id"):1486597426811663%bf6da727bf. 6da727, AnyHashable("rewards"): {"Battle helm":1,"Gems":1000}, AnyHashable("aps"): {
alert = "Achievement Completed";
}]
So how do convert that to a usable variable?
AnyHashable("rewards"): {"Battle helm":1,"Gems":1000}, AnyHashable("aps"): {
alert = "Achievement Completed";
}
The returned item is called userInfo so like...
let rewards = userInfo["rewards"] as! [String:Int]
Doesn't work, any help on this would be greatly appreciated! Again I'm in swift 3.0 so swift 3.0 examples could help.
the notification userInfo is parsed as a Dictionary<String, Any> or [String: Any]
let userInfo: [String: Any] = [
"description": "Open 10 common chests.",
"icon": "localhost:8000//media/achievements/Common%20Chest%20Go- Getter/bomb.jpg",
"name": "Common Chest Go-Getter",
"gcm.message_id": "1486597426811663%bf6da727bf. 6da727",
"rewards": [
"Battle helm": 1,
"Gems":1000
],
"aps": [
"alert": "Achievement Completed"
]
]
if let rewards = userInfo["rewards"] as? [String: Any] {
if let battle = rewards["Battle helm"] as? Int {
print(battle) // 1
}
if let gems = rewards["Gems"] as? Int {
print(gems) // 1000
}
}
if let aps = userInfo["aps"] as? [String: Any] {
if let alert = aps["alert"] as? String {
print(alert) // Achievement Completed
}
}
Looks like you are confused with this:
let arrayOfStrings = [String]()
let dictionary = [String: Any]()
let arrayOfDictionaries = [[String:Any]]()

Alamofire Swift 3.0 Extra argument in call

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
}
}

Missing argument for parameter #2 in call to Alamofire.request(URLRequestConvertible)

Trying to pass an Authentication header in, using the recommended approach of a custom URLRequestConvertible.
So here is my URLRequestConvertible object that conforms to the protocol:
class SecureJSONRouter : URLRequestConvertible {
var type: String
var token: String
var parameters: [String: AnyObject]
init(typevar: String, tokenvar: String, parametersvar: [String: AnyObject]) {
type = typevar
token = tokenvar
parameters = parametersvar
}
var URLRequest: NSURLRequest {
let URL = NSURL(string: da_url)!
let URLRequesting = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(type))
let encoding = Alamofire.ParameterEncoding.JSON
URLRequesting.setValue(token, forHTTPHeaderField: "Authorization")
return encoding.encode(URLRequesting, parameters: parameters).0
}
}
It's basically a place to store a few things, like a bit of URL, and a token, and a way to create a NSURLRequest with a full URL, the JSON parameters, and the header field for authorization.
When I try to call it like this:
let myUrlRequest: URLRequestConvertible = SecureJSONRouter(typevar: "locations", tokenvar: token!, parametersvar: parameters)
Alamofire.request(myUrlRequest).response{ (req, resp, data, error) in
if (error != nil) {
println(req)
println(resp)
} else {
println("saved \(data)")
}
}
it won't compile, gives me a "Missing argument for parameter #2 in call" error, at the request line.
Any ideas?
PS: I did have my SecureJSONRouter thingy as the recommended Enum instead of a Class, but I got the same error. I was looking at the protocol definition, and figured there's no reason it can't be a simpler (class) in my case, so I changed it. Still the same error.
I think there's a few possible culprits here. First off, are you sure you're calling Alamofire and not AlamoFire? I've seen people make that mistake before.
As for the sample code you posted, it didn't compile for a few different reasons. I couldn't reproduce exactly the same compiler errors you were seeing, but here's a slightly modified version of you original post that does compile.
class SecureJSONRouter : URLRequestConvertible {
var type: String
var token: String
var parameters: [String: AnyObject]
init(typevar: String, tokenvar: String, parametersvar: [String: AnyObject]) {
type = typevar
token = tokenvar
parameters = parametersvar
}
var URLRequest: NSURLRequest {
let URL = NSURL(string: "http://httpbin.org")!
let URLRequesting = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(type))
let encoding = Alamofire.ParameterEncoding.JSON
URLRequesting.setValue(token, forHTTPHeaderField: "Authorization")
return encoding.encode(URLRequesting, parameters: parameters).0
}
}
Then here's an example of calling your SecureJSONRouter.
let token: String? = "my_fancy_token"
let parameters: [String: AnyObject] = ["sample_parameter": "sample_parameter_value"]
let myUrlRequest: URLRequestConvertible = SecureJSONRouter(typevar: "locations", tokenvar: token!, parametersvar: parameters)
Alamofire.request(myUrlRequest).response{ (req, resp, data, error) in
if (error != nil) {
println(req)
println(resp)
} else {
println("saved \(data)")
}
}
That is compiling with Xcode 6.1.1 against the Alamofire 1.1.3 release. Hope that helps!