send json array to alamofire - ios

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?

Related

How to pass array of Object parameter to Alamofire swift

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

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 multiple array in parameter in swift

I'm calling a service in which I'm trying to send parameter that consist of array within an array and other parameters which are outside from an array. The format in which I have to send parameter is this:
{
"RestID": 0,
"cart": [
{
"childs": [
{
"addon_cat_id": 0,
"id": 0,
"name": "string",
"next_move_id": 0,
"price": 0,
"sort_order": 0,
"type": "string"
}
],
"name": "string",
"price": "string",
"productid": 0,
"qty": 0,
"description": "string"
}
],
"coupon_code": "string",
"coupon_type": "string",
"coupon_value": 0,
"delivery_price": "string",
"discount_amount": "string"
}
This is how I'm sending my parameter in the service:
let parameter:[String:Any] = ["RestID":restaurantId!,
"cart":[["childs":["addon_cat_id":"0",
"id":ItemDataSource.sharedInstance.items[0].itemId!,
"name":ItemDataSource.sharedInstance.items[0].itemName!,
"next_move_id":"",
"price":ItemDataSource.sharedInstance.items[0].itemPrice!,
"sort_order":"",
"type":"string"
]],
["name": ItemDataSource.sharedInstance.items[0].itemName!,
"price": ItemDataSource.sharedInstance.items[0].itemPrice!,
"productid": ItemDataSource.sharedInstance.items[0].itemId!,
"qty": 2,
"description":ItemDataSource.sharedInstance.items[0].itemDdescription!]
],
"coupon_code" : couponCode!,
"coupon_type" : couponType!,
"coupon_value" : couponValue!,
"delivery_price" : deliveryLbl.text!,
"discount_amount" : disocunt!,
"discount_description" : discountDesc!,
"discount_info" : discountInfo!,
"distance": "",
"door_num" : doorTxt.text!,
"firstname" : "",
"lastname" : "",
"order_type" : "Delivery",
"payment_mode" : "",
"phone" : mobileTxt.text!,
"postcode" : postCodeTxt.text!,
"preorder" : true,
"preorder_is_preorder" : "",
"street" : address1Txt.text!,
"token" : "",
"town" : addressTxt2.text!,
"total": self.grandTotalLbl.text!,
"stripeToken" : "",
"customer_id" : "2",
"preordertime": preOrderTime,
"usercmt": "descri",
"email": userEmail!
]
But when I call the service I get an error. I have discussed this with the server side and they are saying it is a mistake in sending the parameter. How can I send multiple arrays within an array in parameter?
This is my service class:
class SaveOrderDeliveryService{
static let instance = SaveOrderDeliveryService()
var status:Int = 0
func saveOrderDelivery(param:[String:Any],completion:#escaping CompletionHandler) {
Alamofire.request(saveOrderDeliveryUrl, method: .post, parameters:param, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)")// response serialization result
print(response)
if response.result.error == nil{
self.status = (response.response?.statusCode)!
if(self.status == 200){
print(response)
guard let data = response.data else {return}
do{
if let json = try JSON(data: data).dictionary{
completion(true)
}
}catch let jsonErr{
print(jsonErr)
}
}
completion(true)
}else{
completion(false)
debugPrint(response.result.error as Any)
}
}
}
}
Try this add your data , make sure now one with nil
let parameters = [
"RestID": "",
"cart": [
[
"childs": [
[
"addon_cat_id": "",
"id": "",
"name": "string",
"next_move_id": "",
"price": "",
"sort_order": "",
"type": "string"
]
],
"name": "string",
"price": "string",
"productid": "",
"qty": "",
"description": "string"
]
],
"coupon_code": "string",
"coupon_type": "string",
"coupon_value": "",
"delivery_price": "string",
"discount_amount": "string"
] as [String : Any]
Alamofire.request(saveOrderDeliveryUrl, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
}

Sending JSON object as a post parameter using Alamofire

I'm currently working on an iOS app, and recently I faced an obstacle, basically the API endpoint I'm trying to consume requires a JSON object as a POST parameter in this format.
{
json: {
product_report: [
{
"id_assigned_pos": someid,
"id_user": someid,
"number": somenumber,
},
{
"id_assigned_pos": someid,
"id_user": someid,
"number": somenumber,
},{
"id_assigned_pos": someid,
"id_user": someid,
"number": somenumber,
}
]
}
}
I'm having a hard time figuring out how to achieve this using Alamofire and swift 4.
I'd appreciate someone's help.
Thanks!
let parameters = [
"json": [
"product_report": [
[
"id_assigned_pos": 1,
"id_user": 1,
"number": 1
],
[
"id_assigned_pos": 1,
"id_user": 1,
"number": 1
],
[
"id_assigned_pos": 1,
"id_user": 1,
"number": 1
],
]
]
]
Alamofire.request(url, method:.post, parameters:parameters, headers:headers).responseJSON { response in
// Here is the response
} `
You can try this one:
var dict : [String: Any] = [:]
dict["type"] = "Step"
dict["data"] = ["2015-08-02": 8574];
let params: [String: Any] = ["r_id": "someName",
"data": String.jsonString(data: dataDict)];
Here jsonString is an extension of String
static func jsonString(data : Any) -> String {
var jsonString = "";
do {
let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
} catch {
print(error.localizedDescription)
}
return jsonString;
}

alamofire extra argument in call

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

Resources