Extra argument 'method' in call in Swift 3.0 - swift3

I'm getting this error : Extra arguement in 'method' in call. I am using XCode 8, Swift 3.0 and iOS 10.0.
I'm attaching the screenshots for the code.

try once below code
Alamofire.request("Your URL", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
break
case .failure(_):
break
}
}

Need to change in your code
encoding:URLEncoding.httpBody
to
encoding:URLEncoding(destination: .httpBody)
Try this in your code for New Alamofire 4.0
Swift 3
Alamofire.request(requestURL, method: .post, parameters: parameters, encoding:URLEncoding(destination: .httpBody), headers: headers)
.responseJSON { response in
switch response.result {
case .success:
self.successGetData(response.result.value! as AnyObject)
case .failure(let error):
print(error)
}
}
Source : - Alamofire 4.0

Related

Alamofire Extra argument 'method' call

let params = "name=Thobio Joseph&googleid=24356567890uyy4546&email=jthobio2#gmail.com&avatar=https://media.licdn.com/mpr/mpr/shrinknp_200_200/AAEAAQAAAAAAAAv0AAAAJDZjZGJjMTFjLWNiNzAtNGYzNy1iMDE4LTA2MzBmNzUwZGExNQ.jpg"
func postMethodUploadDataToServerLoginPage() {
Alamofire.request(loginUrl, method:.post,parameters:params.data(using: String.Encoding.utf8),encoding:URLEncoding.default).responseJSON { response in
switch response.result {
case .success:
print(response)
case .failure(let error):
failure(0,"Error")
}
}
First your params are wrong you need to pass a dictionary [key:value] and then you need to convert it to json and put in your request body, also if you are using Alamofire.request you don't need pass urlString, only a request, try with this code
func postMethodUploadDataToServerLoginPage() {
let paramToSend = ["name":"Thobio Joseph","googleid":"24356567890uyy4546","email":"jthobio2#gmail.com","avatar":"https://media.licdn.com/mpr/mpr/shrinknp_200_200/AAEAAQAAAAAAAAv0AAAAJDZjZGJjMTFjLWNiNzAtNGYzNy1iMDE4LTA2MzBmNzUwZGExNQ.jpg"]
let request = NSMutableURLRequest(url: URL(string: loginUrl)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters)
Alamofire.request(request).responseJSON { (response) in
switch response.result {
case .success:
print(response)
case .failure(let error):
failure(0,"Error")
}
}
Hope this helps

Expression type 'DataRequest' is ambiguous without more context Swift 3

I am newbie and I have an error that I don't know how to fix, so I would appreciate all the helps. I am migrating from swift 2 to swift 3 and I get this error:
Expression type 'DataRequest' is ambiguous without more context
Here is my code:
static func renewToken(_ onSuccess: #escaping (JSON) -> Void, onFailure: #escaping (NSError) -> Void) {
let token = DataManager.token?.token
let header = ["Authorization": "Bearer "+token!]
Alamofire.request("\(BASE_URL)\(RENEWTOKEN_PATH)", method: .get, parameters: nil, encoding: .JSONEncoding.default, headers: header)
.validate()
.responseJSON { response in
switch response.result{
case .Success(let jsonObj):
onSuccess(JSON(jsonObj))
case .Failure(let error):
onFailure(error)
}
}
}
Your error is misleading you need to make 3 changes with your code.
With encoding its not .JSONEncoding.default but simply JSONEncoding.default
With Alamofire 4.* and Swift 3.* case .Success and .Failure of Result enum is now write in lowercase like .success and .failure.
From Swift 3 use Error instead of NSError.
So whole code goes like this.
static func renewToken(_ onSuccess: #escaping (JSON) -> Void, onFailure: #escaping (Error) -> Void) {
let token = ""
let header = ["Authorization": "Bearer "+token]
Alamofire.request("", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: header)
.validate()
.responseJSON { response in
switch response.result{
case .success(let jsonObj):
onSuccess(JSON(jsonObj))
case .failure(let error):
onFailure(error)
}
}
}

Alamofire request response?

I am using this Alamofire request and returning a json
let todoEndpoint: String = "https://api.abc.com/api/v3/products?pid=uid8225&format=json&&offset=0&limit=10"
Alamofire.request(todoEndpoint)
.responseJSON { response in
guard let json = response.result.value as? [String: Any] else {
print("didn't get todo object as JSON from API")
print("Error: \(response.result.error)")
return
}
print(json)
}
Now i have do loop where i want to use this json value but i am getting:
error : Use of unresolved identifier json ?
do {
for (index,subJson):(String, JSON) in json {
print("Index :\(index) Title: \(subJson)" )
} catch
{
print("there was an error")
}
As mentioned :
https://github.com/Alamofire/Alamofire#response-string-handler
" the result of a request is only available inside the scope of a response closure. Any execution contingent on the response or data received from the server must be done within a response closure."
How can i use this json value outside scope of response closure ?
Can you please suggest
Is there any completion handler i need to write and how can it be done ?
Thanks
Better use the SwiftyJson for easy json parsing with Almofire like bellow :
import Alamofire
import SwiftyJSON
static func getRequest(urlString: URL?, Parameter:NSDictionary?, completion: #escaping (_ serverResponse: AnyObject?,_ error:NSError?)->()){
Alamofire.request(urlString!, parameters:nil, headers: nil).responseJSON { response in
if(response.result.value != nil){
let serverResponse = JSON(response.result.value!)
print("Array value is \(serverResponse.arrayValue)")
completion(serverResponse as AnyObject?, nil)
}
else{
completion(nil, response.result.error as NSError?)
}
}
}
You can write this function in a separate class like NetworkLayer and then call it from any class for the WebService call as given bellow :
let url = NSURL(string: yourWebServiceUrlString)
NetworkLayer.getRequest(urlString: url as URL?, Parameter: nil) { (serverResponse, error) in
if (error == nil){
print("Server response: \(serverResponse)")
}
}
Note: You can also pass the parameter dictionary in it.

Alamofire not hit the API and set the header

I am using Alamofire for api call. but not hit the API. And also how to set the header in Alamofire.
func signupApiASyncPostCall(_ url:String, params:[String: AnyObject]?, success successBlock :#escaping apiSuccess,failure failureBlock :#escaping apiFailure) {
let Auth_header = ["Content-Type" : "application/json", "application/json" : "Accept"]
Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.default, headers: Auth_header)
.responseJSON { response in
print("\(response.request?.url)") // original URL request
//print(response.response) // URL response
//print(response.data) // server data
print(response.result) // result of response serialization
if response.result.isSuccess {
successBlock(response.result.value as? NSDictionary)
print(successBlock(response.result.value as? NSDictionary))
} else {
let httpError: NSError = response.result.error! as NSError
let statusCode = httpError.code
let error:NSDictionary = ["error" : httpError,"statusCode" : String(statusCode)]
failureBlock(error)
}
}
}

Can anyone give me example on AFNetworking 3.0 in post method?

I am struck on it because there is no AFHTTPRequestoperation to find difficult on it. please use on afnetworking 3.0 in swift.
AFHTTPRequestoperation class removed in Afnetworking 3.0
https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-3.0-Migration-Guide
Try this:
func PostData(){
let parameters : NSMutableDictionary? = [
"UserID": String(300),
"UserProfileID": String(356)]
let manager = AFHTTPSessionManager()
let serializerRequest = AFJSONRequestSerializer()
serializerRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
manager.requestSerializer = serializerRequest
let serializerResponse = AFJSONResponseSerializer()
serializerResponse.readingOptions = JSONSerialization.ReadingOptions.allowFragments
serializerResponse.acceptableContentTypes = ((((NSSet(object: "application/json") as! Set<String>) as Set<String>) as Set<String>) as Set<String>) as Set<String>;
manager.responseSerializer = serializerResponse
manager.post(Webserive.DefaultProfile, parameters: parameters, progress: nil, success: { (task: URLSessionDataTask, responseObject: Any?) in
if (responseObject as? [String: AnyObject]) != nil {
print("responseObject \(responseObject)")
}
}) { (task: URLSessionDataTask?, error: Error) in
print("POST fails with error \(error)")
}
}
Just use Alamofire if you need to implement it on swift. Check answer here which shows example of Alamofire post method.