How to successfully pass string array as parameter alamofire - ios

I have an endpoint that accepts a string array as parameter but I can't get it working with alamofire.
I test my endpoint with postman and it works fine, even in the browser, but with alamofire it fails and just returns the whole thing (as if I didn't put any parameter).
func getQuotes(String url){
//THIS CALL IS NOT WORKING. PARAMETERS ARE NOT SENT PROPERLY - FIX
let stringArray : [String] = ["4250_XSAU", "Test"]
let getQuoteParameters : Parameters = [
//"internal_symbols": stockInternalSymbols
"internal_symbols" : stringArray
]
print("attempting to get quotes on utility queue")
Alamofire.request(url, parameters: getQuoteParameters).responseJSON{ response in
print(response)
/* if (response.result.value != nil){
let jsonResponse = JSON(response.result.value!)
print(jsonResponse)
}
*/
}
}
Am I doing something wrong? When I go to url + "?internal_symbols=["4250_XSAU","Test"] on my browser, or postman, it works just fine.
I also tried setting my "getQuoteParamaters" variable as
let getQuoteParameters : Parameters = [
"internal_symbols" : ["4250_XSAU", "Test"]
]
but it doesn't work neither... it should be the same thing.
Just to clarify, this request ignores completely my parameters, when it should send the array to my backend.

You can simply pass your string array in converting it into a JSON format.Like in the sample code given below:
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let values = ["06786984572365", "06644857247565", "06649998782227"]
request.httpBody = try! JSONSerialization.data(withJSONObject: values)
Alamofire.request(request)
.responseJSON { response in
// do whatever you want here
switch response.result {
case .failure(let error):
print(error)
if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
print(responseString)
}
case .success(let responseObject):
print(responseObject)
}
}

My solution in Swift 3:
let text: [String] = ["location.branches.longitude", "location.branches.latitude"]
let params: Parameters = [
"_source": text
]

Try by add encoding standard in your request, like JSONEncoding.default
func getQuotes(String url){
//THIS CALL IS NOT WORKING. PARAMETERS ARE NOT SENT PROPERLY - FIX
let stringArray : [String] = ["4250_XSAU", "Test"]
let getQuoteParameters : Parameters = [
//"internal_symbols": stockInternalSymbols
"internal_symbols" : stringArray
]
print("attempting to get quotes on utility queue")
Alamofire.request(url, method: .post, parameters: getQuoteParameters, encoding: JSONEncoding.default).responseJSON{ response in
print(response)
/* if (response.result.value != nil){
let jsonResponse = JSON(response.result.value!)
print(jsonResponse)
}
*/
}
Thanks.

Related

Alamofire doesnt allow to send object directly

My API only accepts object as the body , but alamofire only sends Dictionary as an object, which my server is not accepting requesting help
I have to call an API which is a post api using alamofire
as soon as i convert the model to dictionary and dicitionary to json
and post it Alamofire does not allow me to post a string
it allows me to send a dictionary which my api does not accept
["key":"value"]- Not acceptable
{"key":"value"}- Acceptable
Can anyone share any solution?
I am using Swift 5 , Xcode 10, Alamofire 4.8.2
do{
let d = try data.asDictionary()
jsonString = DictionaryToJSON(data: dictionary)
} catch {
print(error)
}
Alamofire.request(url, method: .post, parameters: jsonString, encoding: .utf8, headers: [: ]).responseJSON { (res) in
print(res.result)
print("Request Data \(res.request) \n Dictionary \(jsonString)")
do {
let d = try JSONDecoder().decode([OTPMessage].self, from: res.data!)
print(d[0].message)
} catch {
print(error)
}
}
// Dictionary to JSON
func DictionaryToJSON(data: [String:Any])->String {
if let theJSONData = try? JSONSerialization.data(
withJSONObject: data,
options: .prettyPrinted
),
let theJSONText = String(data: theJSONData, encoding: String.Encoding.ascii) {
print("JSON string = \n\(theJSONText)")
return theJSONText
}
else {
return ""
}
}
// Object to Dictionary
extension Encodable {
func asDictionary() throws -> [String: Any] {
let data = try JSONEncoder().encode(self)
guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
throw NSError()
}
return dictionary
}
}
//Struct
struct OTPMessage:Codable {
var message = String()
}
You don't have to convert your dictionary to a JSON String because Alamofire can do the encoding, see this example.
I suggest you to change your code to something like this
do{
let dictionary = try data.asDictionary()
Alamofire.request(url, method: .post, parameters: dictionary, encoding: .JSON, headers: [:]).responseJSON { (res) in
print(res.result)
print("Request Data \(res.request) \n Dictionary \(jsonString)")
do{
let d = try JSONDecoder().decode([OTPMessage].self, from: res.data!)
print(d[0].message)
}catch{
print(error)
}
}
} catch{
print(error)
}
With Alamofire you can not do this. What you need to do is creating a URLRequest object and setting the httpBody property of it and then passing it to Alamofire.
URLRequest allows you to have Data as POST body.
var request = URLRequest(url: urlFinal)
request.httpMethod = HTTPMethod.post.rawValue
request.allHTTPHeaderFields = dictHeader
request.timeoutInterval = 10
request.httpBody = newPassword.data(using: String.Encoding.utf8)
Alamofire.request(request).responseString { (response) in
if response.response!.statusCode >= 200 && response.response!.statusCode <= 300 {
completion("success")
}else {
completion("failed")
}
}
here newPassword is string. from there I created the Data object. You have to convert your Custom class object to Data object.

Send Array of Request Body in an Alamofire Request

I have to send an array of request body and following is the request body that i have to send
[{
"user": "abc",
"id": "demo"
}]
What i've tried?
var requestArray = [[String: String]]()
let params = [
"user": "abc",
"id": "demo"
]
requestArray.append(params)
var request = URLRequest(url: URL.init(string: myUrl)!)
request.httpMethod = ".post"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: requestArray)
Alamofire.request(request)
.response{
response in
print("Request Body:- \(response.request)")
print(response)
}
Problems that i am facing
URL works flawlessly in both Postman and an Android App
Above solution is not working for me. My web service returns me 400 error code (Bad Request)
I am new to iOS development so any help will be appreciated.
Guys i have fixed the issue. I was playing around with some of the solutions from you guys and suddenly it worked!
So what was the main problem?
I changed the request.httpMethod = ".post" to request.httpMethod = "post".
Initially this did not work when i commented back to #NiravD but after some time when i did the changes below, i was able to see the output
Additional changes to view the response on console
Replaced .response to .responseJSON
Thanks a lot to everyone who helped :)
First of all Alamofire requires Parameter to be of type [String: Any], and the second you don't need to make a post request like that. No need for JSONSerialization. Try this and it will be ok.
let params: [String: Any] = [
"user": "abc",
"id": "demo"
]
Alamofire.request(URL.init(string: myUrl)!, method: .post, parameters: params)
.validate()
.responseString {
(response) in
print(response)
}
May be you are missing headers. Can you try it adding the headers that you can see n postman?
Please try this
// this should accompaign your required work [[String:Any]]
var requestArray = [AnyObject] // => Array to conatin dictionaries of type [String: Any]
var dictionaryObject = [String: AnyObject] // => to create some dictionary to append in requestArray
dictionaryObject["user"] = "abc"
dictionaryObject["id"] = "demo"
requestArray.append(dictionaryObject)
Alamofire.request(URL.init(string: myUrl)!, method: .post, parameters: requestArray).validate().responseString { (response) in
print(response)
}
You must pass your requestArray from Alamofire.request instead of request
Alamofire.request(requestArray)
manager.request(url, method: .get, headers: AUTH_HEADER).responseJSON { response in
switch response.result {
case .success:
//whatever you want to do in succes
case .failure(let error):
if let del = self.delegate {
//do what you want
}
print(error)
}
}

Replicating post method in Postman with parameters and body-raw into Alamofire

I'm having a problem on using Alamofire. When I try to post a request using a generic parameters like ["name":"John", "age":"27"] it always succeeds. But, when I try to use a web service that requires parameters and a body-raw for a base64 string I'm not able to get a successful response from the server. Though it succeeds when I use Postman. Does anyone knows how to do this on Alamofire 4? Here is the screenshot of my postman.
Thank you!
#nathan- this is the code that I used. I just assumed that the base64String inside the "let paramsDict" has a key value named "data" though it doesn't have a key name in postman.
let urlString = ApiManager.sharedInstance.formsURL + ApiManager.sharedInstance.mobileFormsImageUpload
let paramsDict = ["token": token, "fileID":"2", "filename":"images.png", "data": base64String] as [String : Any]
Alamofire.request(urlString, method: .post, parameters: paramsDict, encoding: URLEncoding.httpBody, headers: [:])
.responseJSON{ response in
switch response.result {
case .success(let data):
debugPrint("SUCCESS")
case .failure(let error):
debugPrint("Request Error")
}
}
I already figured it out. It needs a custom encoding to make it work. All the parameters must be inlined with the url so the base64 string inside the parameter is the only to be encoded. Here is the code that I used.
struct CustomPostEncoding: ParameterEncoding {
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try URLEncoding().encode(urlRequest, with: parameters)
let base64 = parameters?["data"] as! String
let finalBase64Format = "\"" + base64 + "\""
let postData = NSData(data: finalBase64Format.data(using: String.Encoding.utf8)!)
request.httpBody = postData as Data
return request
}
}
func uploadImageBase64(){
let jpegCompressionQuality: CGFloat = 0.9 // Set this to whatever suits your purpose
if let base64String = UIImageJPEGRepresentation(testIMG, jpegCompressionQuality)?.base64EncodedString() {
var token = String()
if let data = UserDefaults.standard.data(forKey: "userProfile"),
let user = NSKeyedUnarchiver.unarchiveObject(with: data) as? UserProfile{
token = user.token
} else {
print("There is an issue")
}
let headers = [
"content-Type": "application/json"
]
let urlString = "http://localhost/FormsService.svc/Getbase64?filename=test.png&fileID=1151&token=80977580xxx"
let paramsDict = ["data": base64String] as [String : Any]
Alamofire.request(urlString, method: .post, parameters: paramsDict, encoding: CustomPostEncoding(), headers: headers)
.responseJSON{ response in
print("response JSON \(response.result)")
}
.response{ response in
print("RESPONSE \(response)")
}
}
}

Post method request Alamofire

I'm using Swift 3 and Alamofire 4.0.
I want to create similar Alamofire POST request as Postman request shown in screenshot:
I've tried with these lines of code:
var parameters: [String: Any] = [
"client_id" : "xxxxxx",
"client_secret" : "xxxxx",
"device_token" : "xxxx",
"fullname" : "xxxxx",
"gender": "xxx"
]
Alamofire.request(url, method: .post, parameters: parameters).responseJSON { response in
print(response)
}
But I got this error:
How to implement POST request with Body as form-data using Alamofire in Swift 3?
Swift 3.0 - Alamofire - Working code for multipart form data upload *
// Parameters
let params: [String : String] =
["UserId" : "\(userID)",
"FirstName" : firstNameTF.text!,
"LastName" : lastNameTF.text!,
"Email" : emailTF.text!
]
// And upload
Alamofire.upload(
multipartFormData: { multipartFormData in
for (key, value) in params
{
multipartFormData.append((value.data(using: .utf8))!, withName: key)
}
},
to: url,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
upload.uploadProgress(queue: DispatchQueue(label: "uploadQueue"), closure: { (progress) in
})
case .failure(let encodingError):
print(encodingError)
}
}
)
Let me know if you still have issues with it.
after too much try I have succeded so try this
override func viewDidLoad() {
super.viewDidLoad()
let parameters: Parameters = ["client_id": "1","user_token":"xxxxxxxx"]
// Do any additional setup after loading the view, typically from a nib.
let url = "http://xxxxxxxxxxx/index.php/Web_api/get_client_profile"
//let timeParameter = self.getLastTimeStamp()
self.request = Alamofire.request(url, method: .post, parameters:parameters)
if let request = request as? DataRequest {
request.responseString { response in
//PKHUD.sharedHUD.hide()
do{
let dictionary = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
print(dictionary)
}catch{
}
}
}
}
var request: Alamofire.Request? {
didSet {
//oldValue?.cancel()
}
}
You can post a request using Alamofire.
let url = ""
let headers = [ "Content-Type" : "application/json"]
let para : Parameters = [ "data" : JSONObject]
Alamofire.request(url, method: .post, parameters: para, encoding: JSONEncoding.default, headers : headers)
.responseJSON { response in
print(response)
print(response.result)
}
Nothing to worry about.
Alamofire request method not changed so much(For Swift 3.0) if in case you know how to do that in Swift 2.0/2.2. If you understand the old method then you can easily understand this one also. Now lets take a closer look on the following boilerplate -
Alamofire.request(apiToHit, method: .post, parameters: parametersObject, encoding: JSONEncoding.default, headers: headerForApi).responseJSON { response in switch response.result{
case .success(_):
if let receivedData: Any = response.result.value{
if let statusCode: Int = response.response?.statusCode {
//Got the status code and data. Do your data pursing task from here.
}
}else{
//Response data is not valid, So do some other calculations here
}
case .failure(_):
//Api request process failed. Check for errors here.
}
Now here in my case -
apiToHit //Your api url string
.post //Method of the request. You can change this method as per you need like .post, .get, .put, .delete etc.
parametersObject // Parameters needed for this particular api. Same in case you are sending the "body" on postman etc. Remember this parameters should be in form of [String: Any]. If you don't need this then you can just pass nil.
JSONEncoding.default //This the encoding process. In my case I am setting this as .default which is expected here. You can change this to .prettyPrinted also if you need.
headerForApi //This is the header which you want to send while you are requesting the api. In my case it is in [String: String] format. If you don't need this then you can just pass nil.
.responseJSON //Expecting the response as in JSON format. You can also change this as you need.
Now, in my request I am using Switch inside the request closure to check the result like response in switch response.result{.
Inside case .success(_): case I am also checking for result data and http status code as well like this
if let receivedData: Any = response.result.value{
if let statusCode: Int = response.response?.statusCode {
}
}
Hope this helped. Thanks.
class func alamofireMethod(methods: Alamofire.HTTPMethod , url : URLConvertible , parameters : [String : Any],need_flag_inside : Bool = false, paramJson : Bool = true ,need_loader : Bool = true,Header: [String: String],handler:#escaping CompletionHandler,errorhandler : #escaping ErrorHandler)
{
if NetworkController.sharedInstance.checkNetworkStatus()
{
var alamofireManager : Alamofire.SessionManager?
var hed = Header
if let tok = UserDefaults.standard.value(forKey: "TOKEN") as? String {
hed = ["Authorization":"Bearer \(tok)"]
}
if need_loader {
// DELEGATE.showLoader()
}
var UrlFinal = ""
do
{
try UrlFinal = baseURL + url.asURL().absoluteString
}
catch{}
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForResource = 25
configuration.timeoutIntervalForRequest = 25
configuration.httpAdditionalHeaders = hed
alamofireManager = Alamofire.SessionManager(configuration: configuration)
alamofireManager = Alamofire.SessionManager.default
let json = JSON(parameters)
guard let jsonDict = json.dictionaryObject else {
return
}
var jsonData = Data()
do {
jsonData = try JSONSerialization.data(withJSONObject: jsonDict, options: [])
} catch {
//handle error
print(error)
}
var request = URLRequest(url: URL(string: UrlFinal)!)
request.httpMethod = methods.rawValue
if methods == .post || methods == .put
{
//check here
if paramJson {
hed["Content-Type"] = "application/json"
request.httpBody = jsonData
}else{
let postString = self.getPostString(params: parameters)
request.httpBody = postString.data(using: .utf8)
}
}
request.allHTTPHeaderFields = hed
Alamofire.request(request).responseJSON(queue: nil, options: JSONSerialization.ReadingOptions.allowFragments) { (response) in
print(parameters)
print(UrlFinal)
print(hed)
// DELEGATE.hideLoader()
if response.result.isSuccess
{
print(response)
handler(response.result.value! as AnyObject)
}
else if response.response?.statusCode == 401
{
// DELEGATE.redirectToLogin()
// DELEGATE.showToast(message: "Token Expired")
}
else{
// DELEGATE.showToast(message: default_failure)
errorhandler(response.result.error! as NSError)
print(response.result.error as Any)
}
}
}else{
// DELEGATE.showToast(message: "Please check your internet connection.")
}
}
Alomofire With Post and Put Method In swift

How to get response headers when using Alamofire in Swift?

I'm using Alamofire for my Rest (POST) request and getting JSON response seamlessly. But i can access only response body. I want to get response headers. Isn't it possible when using Alamofire?
Here is my code snippet:
#IBAction func loginButtonPressed(sender: UIButton) {
let baseUrl = Globals.ApiConstants.baseUrl
let endPoint = Globals.ApiConstants.EndPoints.authorize
let parameters = [
"apikey": "api_key_is_here",
"apipass": "api_pass_is_here",
"agent": "agent_is_here"
]
Alamofire.request(.POST, baseUrl + endPoint, parameters: parameters).responseJSON {
(request, response, data, error) in let json = JSON(data!)
if let result = json["result"].bool {
self.lblResult.text = "result: \(result)"
}
}
}
As response is of NSHTTPURLResponse type, you should be able to get the headers as followed:
response.allHeaderFields
Here is how to access the response headers in Swift 3:
Alamofire.request(.GET, requestUrl, parameters:parameters, headers: headers)
.responseJSON { response in
if let headers = response.response?.allHeaderFields as? [String: String]{
let header = headers["token"]
// ...
}
}
This code gets response header in Swift 4.2
Alamofire.request(pageUrlStr, method: .post, parameters: Parameter, encoding: URLEncoding.httpBody, headers: nil).responseJSON
{ response in
//to get JSON return value
if let ALLheader = response.response?.allHeaderFields {
if let header = ALLheader as? [String : Any] {
if let cookies = header["Set-Cookie"] as? String {
UserDefaults.standard.set(cookies, forKey: "Cookie")
}
}
}
}

Resources