How to pass array of Object parameter to Alamofire swift - ios

I'm new In Swift anyone help me.
I want to pass array of object to Alamofire and I don't know how to do that
Here is the parameter that required:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZWU4OGZiNzhiYTBkMjMyZDFmYWZkMzgiLCJpYXQiOjE1OTIyOTk2Njh9.AVuxiTZy10fV2ZMZcT-oHXSg6PdK3tfE",
"zipCodes": [
{
"zip_code": "55001",
"city": "Afton",
"state": "MN",
"county": "Washington"
}
]
}
And I do that
let parameters : [String : String] = ["token" : retrivedToken, "zipCodes" : [{
"zip_code": "55001",
"city": "Afton",
"state": "MN",
"county": "Washington"
}]
]

Simply just use your parameter to your request.
func sendRequestRequest() {
// JSON Body
let parameters: [String : Any] = [
"token": retrivedToken,
"zipCodes": [
"county": "Washington",
"state": "MN",
"zip_code": "55001",
"city": "Afton"
]
]
// Fetch Request
Alamofire.request("your API url", method: .post, parameters: parameters, encoding: JSONEncoding.default)
.validate(statusCode: 200..<300)
.responseJSON { response in
if (response.result.error == nil) {
print("HTTP Response Body: \(response.data)")
}
else {
print("HTTP Request failed: \(response.result.error)")
}
}
}
Dont forget, if you use Alamofire v5, use AF.request instead of Alamofire.request

let bodyParams: [String : Any] = [
"token": "\(retrivedToken)",
"zipCodes":[
"county": "Washington",
"state": "MN",
"zip_code": "55001",
"city": "Afton"
]
]
}
let urlString = "abc.com"
Alamofire.request(urlString, method: .post, parameters: bodyParams ,encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}

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
}

How can I post request with order of json in swift with alamofire?

I need a payment method for my app and I have to post a request with JSON data for communicate with API. Everything seem correct to me. I can't find any bug in my code but I assume that JSON not post in order. Is this important? Because response said failure but I can't find anything else. If JSON order is important how can I make it? I'm new in swift please help me.
Here my code:
func mainRequestForPayment() {
)
let headers: HTTPHeaders = [
"accept": "application/json",
"content-type": "application/json",
"authorization": "\(self.authValue)",
"x-iyzi-rnd": "\(self.randomString)",
"cache-control": "no-cache"
]
let url = "MY_URL"
let parameters: [String: Any] = [
"locale": "tr",
"conversationId": "123456789",
"price": "1.1",
"paidPrice": "1.1",
"installment": 1,
"paymentChannel": "WEB",
"basketId": "B67832",
"paymentGroup": "PRODUCT",
"paymentCard": [
"cardHolderName": "CARD_HOLDER_NAME",
"cardNumber": "CARD_NUMBER",
"expireYear": "CARD_YEAR",
"expireMonth": "01",
"cvc": "123",
"registerCard": 0
],
"buyer": [
"id": "BY789",
"name": "John",
"surname": "Doe",
"identityNumber": "74300864791",
"email": "email#email.com",
"gsmNumber": "+905350000000",
"registrationAddress": "Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1",
"city": "Istanbul",
"country": "Turkey",
"zipCode": "34732",
"ip": "85.34.78.112"
],
"shippingAddress": [
"address": "Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1",
"zipCode": "34742",
"contactName": "Jane Doe",
"city": "Istanbul",
"country": "Turkey"
],
"billingAddress": [
"address": "Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1",
"zipCode": "34742",
"contactName": "Jane Doe",
"city": "Istanbul",
"country": "Turkey"
],
"basketItems": [
[
"id": "BI101",
"price": "0.3",
"name": "Binocular",
"category1": "Collectibles",
"category2": "Accessories",
"itemType": "PHYSICAL"
],
[
"id": "BI102",
"price": "0.5",
"name": "Game code",
"category1": "Game",
"category2": "Online Game Items",
"itemType": "VIRTUAL"
],
[
"id": "BI103",
"price": "0.2",
"name": "Usb",
"category1": "Electronics",
"category2": "Usb / Cable",
"itemType": "PHYSICAL"
]
],
"currency": "TRY"
]
Alamofire.request(url, method: .post, parameters: parameters , encoding: JSONEncoding.default, headers: headers)
.responseJSON { (response) in
print(parameters)
switch response.result {
case .success(let value):
let swiftyJson = JSON(value)
print ("return as JSON using swiftyJson is: \(swiftyJson)")
case .failure(let error):
print ("error: \(error)")
}
}
}
Where is my fault I can't see? And again is there any way to make order in post request? Thanks all.
I get that response:
return as JSON using swiftyJson is: {
"conversationId" : "123456789",
"locale" : "tr",
"errorCode" : "1000",
"status" : "failure",
"systemTime" : 1579858355103,
"errorMessage" : "Invalid signature"
}
JSON order isn't typically important, as the JSON spec doesn't define it as a requirement for JSON objects, but some poorly engineered backends do require it. You really need to check the requirements of the backend you're communicating with.
Additionally, Swift's Dictionary type is arbitrarily ordered, and that order may change between runs of your app as well as between versions of Swift used to compile your code.
Finally, Swift's JSONEncoder, and Apple's JSONSerialization type both offer no way to require strict ordering. At most, JSONSerialization offers the .sortedKeys option, which will give you a guaranteed (alphabetical) order, but it may not be the order you declared your parameters in. Using an alternate Encoder, if you have Codable types (which I recommend instead of SwiftyJSON), may give you a better guarantee of order, but you should only really care if it's a requirement of your backend.
As an aside, I suggest you use the static HTTPHeader properties for your HTTPHeaders value, instead of using raw strings, it's much more convenient. For example:
let headers: HTTPHeaders = [.accept("application/json"),
.contentType("application/json")]
Use this class
//////////////////////////////////////////////
import Foundation
import UIKit
import Alamofire
class ServicesClass_New : NSObject
{
var delegate : ServicesClassDelegate!
typealias CompletionBlock = (_ result : Dictionary<String, Any>?, _ error : Error?) -> Void
typealias CompletionDataBlock = (_ result : Data?) -> Void
typealias ProgressBlock = (_ progressData : Progress) -> Void
//MARK: Shared Instance
static let sharedInstance : ServicesClass = {
let instance = ServicesClass()
return instance
}()
static func getDataFromURlWith(url:String,parameters:Dictionary<String, Any>?, requestName:String,completionBlock : #escaping CompletionBlock)
{
print("net available")
Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
switch(response.result) {
case .success(_):
if let data = response.result.value
{
//print(response.result.value!)
//print(data)
var dic : Dictionary<String,Any> = Dictionary()
if data as? Array<Dictionary<String,Any>> != nil
{
dic["data"] = data as? Array<Dictionary<String,Any>>
completionBlock(dic,nil)
}
else
{
completionBlock(data as? Dictionary<String,Any>,nil)
}
}
break
case .failure(_):
print(response.result.error!)
completionBlock(nil ,response.result.error!)
break
}
}
}
static func postDataFromURL(url:String,parameters:Dictionary<String, Any>?, requestName:String,completionBlock : #escaping CompletionBlock)
{
print("net available")
//application/json
//multipart/form-data
let hders : HTTPHeaders = [ "Content-Type" : "application/json"] as [String : String]
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: hders).responseJSON { response in
switch(response.result) {
case .success(_):
if let dict = response.result.value
{
let data = dict as! Dictionary<String,Any>
// print(response.result.value!)
// print(data)
completionBlock(data as Dictionary,nil)
}
break
case .failure(let error):
print((error as NSError).localizedDescription)
completionBlock(nil ,response.result.error!)
print("\(error.localizedDescription)")
break
}
}
}
static func downloadFile(strUrl : String, progressBlock : #escaping ProgressBlock, completionBlock : #escaping CompletionDataBlock)
{
let utilityQueue = DispatchQueue.global(qos: .utility)
Alamofire.request(URL.init(string: strUrl)!).downloadProgress(queue: utilityQueue, closure: { (progress) in
progressBlock(progress)
})
.responseData { (response) in
if let data = response.result.value
{
completionBlock(data)
}
else
{
completionBlock(nil)
}
}
}
static func uploadData(url:String,parameters:Dictionary<String, Any>,requestName:String,arrImg:[UIImage],arrVideos:[URL],completionBlock : #escaping CompletionBlock)
{
print("net available")
let hders = [
"Content-Type": "application/json"
]
Alamofire.upload(multipartFormData:
{
MultipartFormData in
for img in arrImg
{
let imageData = UIImageJPEGRepresentation(img , 0.8)!
MultipartFormData.append(imageData, withName: "image" , fileName:"file\(index).jpg", mimeType:"image/jpeg")
}
index = 0
for video in arrVideos
{
index = index + 1
var videoData : Data = Data()
do
{
videoData = try Data.init(contentsOf: URL.init(fileURLWithPath: video.path))
MultipartFormData.append(videoData, withName: "video", fileName:"file\(index).mp4",mimeType: "video/mp4")
}
catch
{
}
}
for (key, value) in parameters
{
MultipartFormData.append((value as! String).data(using: String.Encoding.utf8)!, withName: key)
}
}, to:url,method:.post,headers:hders, encodingCompletion: {
encodingResult in
//["content-type" : "application/json"]
switch encodingResult
{
case .success(let upload, _, _):
print("image uploaded")
upload.responseJSON { response in
if let JSON = response.result.value
{
print("JSON: \(JSON)")
}
if let dict = response.result.value
{
let data = dict as! Dictionary<String,Any>
print(response.result.value!)
print(data)
completionBlock(data as Dictionary,nil)
}
}
break
case .failure(let encodingError):
completionBlock(nil ,encodingError)
break
}
} )
}
}
/// call protocals where you want to call API.
//There is multiple Methods like : GET, POST
....

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?

How to send form-data using Alamofire 4.0 post request in swift

I am trying to send following JSON data. I am using Alamofire 4.0.
How to pass Data to the server in form-data format?
{
"apikey" : "455feh54b",
"action": "ADD",
"address1" : "Mumbai",
"country" : "India"
"userInfo" : {
"user_detail" :[
{
"name" : "abc",
"age" : 15,
"location" : "Delhi"
},
{"name" : "pqr",
"age" : 20,
"location" : "Mumbai"
}
]
}
}
Here is how you can simply send it
let user_detail = ["name":name, "age":age, "location":location]
let userInfo = ["user_detail": user_detail]
let params = ["apikey":title,
"action":type,
"address":time,
"userInfo":String.JSONStringify(value: user_detail as AnyObject)]
Alamofire.request(url, method:.post, parameters: params, encoding: URLEncoding.default).validate().responseAuthJSON {
response in
switch response.result {
case .failure(let error):
print(error)
self.showAlert(title: "Saving note failed! Please, try again.", message: "")
case .success(let responseObject):
print("response is success: \(responseObject)")
}
}
As they've documented here.You can pass JSON data like following.
let parameters: Parameters = [
"foo": [1,2,3],
"bar": [
"baz": "qux"
]
]
// Both calls are equivalent
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding(options: []))
// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}
let param : Parameters = [
"id":62393,
"userName": "Furkan",
"isActive":true,
]
let header : HTTPHeaders = [Value :"Key"]
Alamofire.upload(
multipartFormData: { multipartFormData in
for (key, value) in Body {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
},
to: urlStr,
headers: header,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseString { response in
print(response as Any)
}
.uploadProgress { progress in // main queue by default
}
return
case .failure(let encodingError):
debugPrint(encodingError)
}
})
Please try this for post form data using Alamofire
let param : Parameters = [
"id":62393,
"userName": "Furkan",
"isActive":true,
]
let header : HTTPHeaders = [Value :"Key"]
Alamofire.upload(
multipartFormData: { multipartFormData in
for (key, value) in Body {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
},
to: urlStr,
headers: header,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseString { response in
print(response as Any)
}
.uploadProgress { progress in // main queue by default
}
return
case .failure(let encodingError):
debugPrint(encodingError)
}
})
Please try this for post form data using Alamofire

Sending JSONObject in Alamofire

How can I send a JSON format like this using Alamofire 4.2.0 :
This is part from my script :
{
"session":{
"email": "user1#gmail.com",
"password": "secret123"
}
}
Thank you !
You can just struct your data in Dictionary and use JSONEncoding.default as encoding to send your request.
let mydata: [String: [String: String]] = [
"session": [
"email": "user1#gmail.com",
"password": "secret123"
]
]
Alamofire.request(url, method: .post, parameter: mydata, encoding: JSONEncoding.default, headers: nil)

Resources