Send multiple array in parameter in swift - ios

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
}

Related

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 request with JSONEncoding giving an error

I am getting an error while passing JSON object as a parameter in Alamofire.request
func apiCall2(anyBaseUrl: String = "", apiFunction: ApiName, method m: HTTPMethod = .get,
parameters: [String: Any]? = nil, isJsonEncoding: Bool = false,
completion: #escaping (Bool, Any?, Error?) -> Void) {
var requestUrl = "\(ActiveBaseURL())\(apiFunction.rawValue)"
if anyBaseUrl != "" {
requestUrl = "\(anyBaseUrl)\(apiFunction.rawValue)"
}
var param = [String: Any]()
if let p = parameters {
param = p
}
Alamofire.request(requestUrl, method: m, parameters: param, encoding: isJsonEncoding ? JSONEncoding.default: URLEncoding.default)
.authenticate(user: ApiUserName, password: ApiPassword)
.responseJSON(options: .allowFragments) { response in
print("request body: \(response.request?.httpBody)")
if response.result.isSuccess {
}
print(response.result.error?.localizedDescription)
completion(false, nil, response.result.error)
}
}
My actual JSON format is
{ "discount_code" : "", "giftcard_code" : "", "dt" :
"2018-11-15", "shipping" : {
"state" : "sel",
"name" : "Test",
"address1" : "testevhsd",
"city" : "test city",
"address2" : "testfhd",
"mobile" : "89464633",
"shipment_code" : "YES",
"postal" : "672673",
"country_id" : "129" }, "iccid" : "", "uid" : "3592", "product" : [
{
"id" : 104,
"type" : "countryPlan",
"qty" : 1
} ] }
And this is how I am passing the JSON in function
var parms: Parameters {
return [
"uid": "3592",
"product": [
["id": 104,"type":"countryPlan", "qty": 1]
],
"shipping": ["name":"Test", "mobile": "89464633", "address1": "testevhsd",
"address2": "testfhd", "city": "test city", "state": "sel",
"postal": "672673", "shipment_code": "YES", "country_id": "129"],
"discount_code": "",
"dt":"2018-11-15",
"giftcard_code": "",
"iccid": ""]
}
Service.shared.apiCall2(apiFunction: .CheckOut, method: .post, parameters: parms, isJsonEncoding: true) { (success, data, _) in
My Error
"JSON could not be serialized because of error:\nThe data couldn’t be read because it isn’t in the correct format."
Initially I thought this is because of web service not able to return the correct JSON but I was wrong if I run same service from postman it is working fine and I am getting data in JSON format
I feel the error is because for JSON data passing

Getting json response but not able to parse in to label

I am getting response in json format and i have array in to array but I am not able to under stood how to print on label i saw my code here
I am getting response of business_time array value so can any one please help
func CallAPI() {
let preferences = UserDefaults.standard
let uid = "u_id"
let acctkn = "acc_tkn"
if preferences.object(forKey: uid) == nil {
// Doesn't exist
} else {
let u_id = preferences.object(forKey: uid) as! String
print(u_id)
let acc_tkn = preferences.object(forKey: acctkn) as! String
print(acc_tkn)
let userprofile = ["user_id":u_id,"access_token":acc_tkn]
SVProgressHUD.show(withStatus: "Loading...")
Alamofire.request(businessDetailByUserId, method: .post, parameters: userprofile).responseJSON
{
response in
//printing response
print(response)
let result = response.result.value
// let obj=result
if result != nil{
let data = result as! [String : AnyObject]
let userdata = data["data"] as! NSDictionary
let userTimings = userdata["business_time"]
print(userTimings)
SVProgressHUD.dismiss()
}
}
}
}
and here is my response::
{
"success": "1",
"data": {
"bus_usr_id": "12",
"fk_user_id": "88",
"fk_cate_id": "2",
"bus_name": "AutoMobiles",
"bus_logo": "https://www.kwikmypay.com/mode_share/modeshare_admin/assets/images/business/bus_uvbdt1531395509.png",
"bus_address": "404 Palladium",
"bus_email": "mihir#hemshub.com",
"bus_website": "www.hemshub.com",
"bus_desc": "All types of automobiles spare parts are available.",
"fav_status": 1,
"bus_contact_no": "9876543210",
"bus_status": "1",
"sub_cate_list": "Spare Parts",
"category": "Automobiles",
"business_time": [
{
"tbl_bus_time_id": "107",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Monday",
"start_time": "17:7",
"end_time": "23:7",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "108",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Tuesday",
"start_time": "17:7",
"end_time": "23:7",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "109",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Wednesday",
"start_time": "17:7",
"end_time": "23:7",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "110",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Thursday",
"start_time": "17:7",
"end_time": "23:7",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "111",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Friday",
"start_time": "17:7",
"end_time": "23:8",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "112",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Saturday",
"start_time": "17:7",
"end_time": "23:8",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "113",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Sunday",
"start_time": "17:7",
"end_time": "23:8",
"status": "1",
"created_date": "2018-07-12 11:38:29"
}
]
},
"message": ""
i want to print values of business_time array on label but i am new to swift so can any one please tell me how to print
if let jsonData = response.result.value as? [String : Any],
let userdata = jsonData["data"] as? [String: Any]
let businessJsonArray = userdata["business_time"] as? [[String: Any]] {
for businessJson in businessJsonArray {
let id = businessJson["tbl_bus_time_id"]
}
}
SVProgressHUD.dismiss()
Above pattern is old. Apple release JsonEndcoder() in swift 4 which you should try.
As you mentioned the value for key business_time is an array so you get multiple items.
Basically don't use NSDictionary and NSArray in Swift, you throw away the important type information and a JSON dictionary in Swift 3+ is always [String:Any], never [String:AnyObject]
//printing response
print(response)
//don't check for `nil`, use optional bindings for all objects
if let result = response.result.value as? [String : Any],
let userdata = result["data"] as? [String : Any],
let userTimings = userdata["business_time"] as? [[String : Any]] {
for timing in userTimings {
print(timing["start_time"] as! String)
print(timing["end_time"] as! String)
}
}
SVProgressHUD.dismiss()
As you can see in each JSON there is response sector responsible for server status (200 = success etc).
Next part is data... so basically, you have several important dictionaries (header, data). To output data without alamofire:
Write to me the response.
func CallAPI()
{
let url = URL(string: "https:// your_Address")!
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let _ = response, let data = data
{
let result = String(data: data, encoding: .utf8)!
print(result as NSString)
} else {
print(error as Any)
}
}
task.resume()
}

swift parsing desc and parsing selected element

Swift parsing desc and parsing selected element. I want to parse desc and after parsing desc parse desc content. thanks swift parsing desc and parsing selected element.
I have tried different methods. Does anyone have an idea on how we can make it possible? I tried the following code:
**Code for getting the data**
func demoApi1() {
Alamofire.request("", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
guard let json = response.result.value as! [[String:Any]]? else{ return}
print("Ang Response: , \(json)")
for item in json {
self.getAllDetail.append(item )
if let desc = item["dec"] as? String {
self.titleArray.append(desc)
print("motherfucker:" , self.titleArray)
}
}
if !self.getAllDetail.isEmpty{
DispatchQueue.main.async {
}
}
break
case .failure(_):
print("Error")
break
}
}
}
Response:
Ang Response [["status": {
name = ongoing;
}, "sched": 2018-04-10T14:22:00+08:00, "desc": asdasdasdsa, "id": 224, "reward": 1.00, "parent": das, "child": dasdas, "date_created": 2018-04-19T15:54:24.657644+08:00, "name": sad, "occurrence": {
name = once;
}, "type": , "date_modified": 2018-04-19T15:54:24.703520+08:00], ["status": {
name = ongoing;
}, "sched": 2018-04-19T15:54:24.657644+08:00, "desc": {
"questions" : [
{
"b" : 2,
"a" : 1
},
{
"b" : 3,
"a" : 2
},
{
"b" : 2,
"a" : 8
},
{
"b" : 9,
"a" : 7
},
{
"b" : 3,
"a" : 6
}
],
"operation" : "addition"
}, "id": 226, "reward": 1.00, "parent": shit, "child": , "date_created": 2018-04-23T14:16:35.739436+08:00, "name": chorename, "occurrence": {
name = once;
}, "type": homework, "date_modified": 2018-04-23T14:16:35.790237+08:00]]
String to Dictionary:
func stringToDictionary(_ strToJSON : String)-> [String:Any]{
print("JsonString:\(strToJSON)")
let data = strToJSON.data(using: .utf8)
var dict = [String:Any]()
do {
dict = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
return dict
}
catch let error as NSError {
print("Error is:\(error)")
}
return dict
}
Use it like this:
let dictConv = stringToDictionary("your_string")
print(dictConv)

Get value from server reponse swift

I am new to Swift,
I want to get value of latitude and longitde from server reponse.
How do i get the value?
Here is my code:
WebServiceHelper.sharedInstance.makeWebServiceCall(urlAddress: "http://jsonplaceholder.typicode.com/users/1", requestMethod: "GET", params: ["Key" : "value"], Success: { (JSON:Any) in
print("Success Received data is: \(JSON)")
}, Error: { (JSON:Any) in
print("Error Received data is: \(JSON)")
}) { (JSON:Any) in
print("Header Received data is: \(JSON)")
}
I am able to get server reponse Here it is:
Success Received data is: {
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"latitude": "-37.3159",
"longitude": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
How do i get?
you can try like this to get lat long :
if let result = JSON as? [String:AnyObject]{
let address = result?["address"] as? [String:AnyObject]
let geo = address?["geo"] as? [String:AnyObject]
print(geo?["lng"])
print(geo?["lat"]) }

Resources