alamofire extra argument in call - ios

Facing this issue from past 2 days. I have updated the pod, updated pod version from 4.0.1 to 4.5.0 but the problem is still the same.
here is my code:
var params: Parameters = [:]
params = [
"id": fetchFromCoreData(keyVlue: "trsptrRegistrationId") as AnyObject,
"mobileNumber": fetchFromCoreData(keyVlue: "mobileNO") as AnyObject,
"isNotification": isnotifyTag as AnyObject
]
print(params)
let auth_token = fetchFromCoreData(keyVlue: "Auth_Token")
let headers = [
"authKey": auth_token
]
print(headers)
let URL: String = GlobalUrls.BASE_URL + GlobalUrls.notifySetting
print(URL)
Alamofire.request(URL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers)

can you please try this way
var param :Parameters
param = [
"id": "Any id",
"mobileNumber": "any mobile number",
"isNotification": "is notification"
]
print(param)
let auth_token = "your auth_token"
let headers = [
"authKey": auth_token
]
print(headers)
let base_url: String = "Here is my base URL"
print(base_url)
Alamofire.request(base_url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: headers).responseJSON(completionHandler: {(resObj) -> Void in
print(resObj)
if resObj.result.isSuccess
{
print("Sucess result")
}
if resObj.result.isFailure
{
let error : Error = resObj.result.error!
print("Fail result")
print(error.localizedDescription)
}
})

Related

How to Arrangement array before send request to alamofire in swift

let request = NSMutableDictionary()
request.setDictionary([ "merchant_reference":getRandomMerchant, "merchant_identifier":"e54638eb", "access_code":"hRRVGXrIpHSYoH19Ebwt", "signature": base64Str, "service_command":"OTP_GENERATE", "language":"en", "payment_option":"VALU", "phone_number":"01008606003", "merchant_order_id":getRandomMerchant, "amount":getTotal, "currency":"EGP", "products":[ [ "product_name": getName, "product_price": getTotal, "product_category":getProductType ] ] ])
Alamofire.request(URLAPi.URL_Payment_Api ,
method : .post ,
parameters : (request as! Parameters) ,
encoding: JSONEncoding.default
).responseJSON { (response) in
debugPrint(response)
if response.result.isSuccess {
let jsonpayfortrequest : JSON = JSON(response.result.value!)
var resultsArray = jsonpayfortrequest.arrayValue
var sortedResults = resultsArray.sorted { $0.stringValue > $1.stringValue }
print(jsonpayfortrequest)
print(resultsArray)
print(sortedResults)
print(jsonpayfortrequest.sorted(by: {$0 > $1}))
let passobjectforrootclasspayfort = OTPGenrateModel(fromJson: jsonpayfortrequest)
print(passobjectforrootclasspayfort.transaction_id!)
SVProgressHUD.dismiss()
} else {
print("error connection") SVProgressHUD.dismiss()
}
}
Try this way, Hope, that will fixe your issue. If it doesn't, please reply
let parameters: [String: Any] = [
"merchant_reference":getRandomMerchant,
"merchant_identifier":"e54638eb",
"access_code":"hRRVGXrIpHSYoH19Ebwt",
"signature": base64Str,
"service_command":"OTP_GENERATE",
"language":"en",
"payment_option":"VALU",
"phone_number":"01008606003",
"merchant_order_id":getRandomMerchant,
"amount":getTotal,
"currency":"EGP",
"products": [
[
"product_name": getName,
"product_price": getTotal,
"product_category":getProductType
]
]
]
Alamofire.request(URLAPi.URL_Payment_Api , method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
// Insert your code here
}

send json array to alamofire

product:[{"id":1,"qty":5,"price":5000},{"id":2,"qty":10,"price":7500}]
user_id:12
lon:112
lat:-7
lokasi:ada
tanggal:12-05-2019
How send that all parameter with Alamofire? Here is my attempt:
let par : [String:Any] = [ "product": productItem,
"user_id": myID(),
"lon":data["longitude"] ?? "",
"lat": data["latitude"] ?? "",
"lokasi":data["location"] ?? "",
"tanggal": data["tanggal"] ?? ""
]
let header = [
"Accept":"application/json",
"Content-Type":"application/json"
]
Alamofire.request("URL", method: .post,parameters: par,encoding: JSONEncoding.default, headers: header).responseJSON
{ response in
}
I don't know what should I do?

Alamofire: send parameter

I want to post data as parameter like this:
{
"data":
[
{
"nik" : "lalaal"
}
]
}
How do I write to these parameters in Swift 3 using Alamofire?
i tried :
let parameter: Parameters = [
"data":[[
"nik" : self.nik,
"check_type" : "IN",
"tanggal" : "01-08-2017 18:22:00",
"long" : String(locationList[projectChoosen].long!),
"lat" : String(locationList[projectChoosen].lat!),
"id_loc" : locationList[projectChoosen].id_project,
"id_project" : nil,
"nama_project" : locationList[projectChoosen].nama_project,
"barcode" : "",
"foto": "",
"mime_type" : "image/jpeg"
]]
]
You can use below code.
let dicRequest: NSDictionary = ["userid" : "test", "password" : "test123"]
let postParams:NSDictionary = [
"data": dicRequest
]
let requestURL: String = String(format: "%#/Login", serverURL)
Alamofire.request(requestURL, method: .post, parameters: postParams as? [String : AnyObject], encoding: JSONEncoding.default, headers: [:])
.responseJSON { response in switch response.result {
case .success(let JSON):
print("response :-----> ",response)
case .failure(let error):
print("Request failed with error: \(error)")
}
}
You can create a Dictionary object first in this formate
{
"data":
[
{
"nik" : "lalaal"
}
]
}
After that you can convert this using NSJSONSerlisation to json string
And than post using Almofire.
let array: [[String: String]] = [["nik": "lalaal"]]
let data = try JSONSerialization.data(withJSONObject: array, options: JSONSerialization.WritingOptions.prettyPrinted)
let string = String(data: data, encoding: String.Encoding.utf8)
let postParam: [String: String] = ["data": string]
let _ = Alamofire.request(apiType.url!, method: apiType.type!,parameters: postParam, encoding: JSONEncoding.prettyPrinted, headers: nil).validate(statusCode: 200..<500).responseJSON { (response) in
}
Here is a sample request using Alamofire and posting a dictionary as parameters:
let dataArray: [[String: String]] = [["nik": "lalaal"]]
let param: [String: [Any]] = ["data": dataArray]
Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: nil).responseJSON { response in }
I use :
let dataIn: [String: String] = ["param1": "value1"]
let paramGo: [String: [String: String]] = ["data_title": dataIn]
Alamofire.request(url, method: .post, parameters: paramGo, encoding: JSONEncoding.default, headers: nil).responseJSON { response in }

Yelp get request not working

When i do the same request in Postman everything is fine but when i try it in Alamofire i get an error.
I'm user Alamofire in swift for the request. Here is my code.
let parameters: Parameters = ["term": searchTerm as AnyObject, "location": "Washington DC" as AnyObject]
// let headers: HTTPHeaders = [tokenType!: accessToken!]
Alamofire.request("https://api.yelp.com/v3/businesses/search", method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: ["Authorization": "Bearer Access_token_************************"])
Error text:
{
error = {
code = "VALIDATION_ERROR";
description = "Please specify a location or a latitude and longitude";
};

Alamofire not sending the current headers (swift)

I keep getting "error_type":"OAuthException","code":"41" when I using alamofire or even when i made it through to the server I got data from before header's authorisation. I think it keep sending same header, how to make sure that alamofire send the current headers?
let headers = ["Authorization" : "\(AccessToken) \(TokenType)"]
print(headers)
Alamofire.request(.GET, "url/profile/", headers: headers, encoding: .JSON).responseJSON { response in
switch response.result {}
EDIT
First, I use login API
let parameters = [
"client_id": "\(Constant.clientId)",
"client_secret": "\(Constant.clientSecret)",
"response_type": "\(Constant.responseType)",
"scope" : "\(Constant.scope)",
"redirect_uri": "\(Constant.redirect)",
"email": "\(email!)",
"password": "\(pass!)"
]
print(parameters)
Alamofire.request(.POST, "http://url/login/", parameters: parameters, encoding: .JSON).responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
print("JSON: \(json)")
let accessToken = json["access_token"].string!
let refreshToken = json["refresh_token"].string
let tokenType = json["token_type"].string!
let expiresIn = json["expires_in"].string
}
And then, I use accessToken and tokenType for authorization
if(refreshToken != nil)
{
let headersCust = ["Authorization" : "\(accessToken) \(tokenType)"]
print(headersCust)
Alamofire.request(.GET, "http://goodies.co.id/api/v1/customer/profile/", headers: headersCust, encoding: .JSON).responseJSON { response in {}
Usually this problem is caused by Redirection. Using some networking debugging tool like Proxyman helps you to understand if this is a case; if so :
this is Alamofire 5(AF 5) solution:
let headers: [String:String] = [...]
let params: [String: Any] = [...]
let url = URL(...)
let redirector = Redirector(behavior: Redirector.Behavior.modify({ (task, urlRequest, resp) in
var urlRequest = urlRequest
headers.forEach { header in
urlRequest.addValue(header.value, forHTTPHeaderField: header.key)
}
return urlRequest
}))
//use desired request func of alamofire and your desired enconding
AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in
//handleDataResponse...
}.redirect(using: redirector)
I hope you are using the latest Alamofire so here is the code for .GET Request:
let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Content-Type": "application/x-www-form-urlencoded"
]
Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
.responseJSON { response in
debugPrint(response)
}
Reference: https://github.com/Alamofire/Alamofire
Try this out! And make sure you are sending the proper headers.

Resources