Getting json response but not able to parse in to label - ios

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

Related

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
}

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

need only key(Status) and value(0) from json in swift 3

{
"items": [
{
"startTime": "1498667581661",
"endTime": "1498667821661",
"dateTime": "2017-06-28T16:33:01.661Z",
"totalTime": "4",
"auctionName": "Bbbb",
"status": 1,
"id": "4760417733705728",
"kind": "auctionTimeApi#resourcesItem"
},
{
"startTime": "1498772812087",
"endTime": "1498772992087",
"dateTime": "2017-06-29T21:46:52.087Z",
"totalTime": "3",
"auctionName": "sdasdasdd",
"status": 1,
"id": "5080491044634624",
"kind": "auctionTimeApi#resourcesItem"
},
{
"startTime": "1498833895423",
"endTime": "1498834375423",
"dateTime": "2017-06-30T14:44:55.423Z",
"totalTime": "8",
"auctionName": "Boston",
"status": 1,
"id": "5085211482128384",
"kind": "auctionTimeApi#resourcesItem"
},
{
"startTime": "1498767894987",
"endTime": "1498768254987",
"dateTime": "2017-06-29T20:24:54.987Z",
"totalTime": "6",
"auctionName": "Dfddd",
"status": 0,
"id": "5111065843073024",
"kind": "auctionTimeApi#resourcesItem"
},
{
"startTime": "1498640043323",
"endTime": "1498640283323",
"dateTime": "2017-06-28T08:54:03.323Z",
"totalTime": "4",
"auctionName": "Andsda",
"status": 1,
"id": "5118511437316096",
"kind": "auctionTimeApi#resourcesItem"
},
{
"startTime": "1498807228606",
"endTime": "1498807348606",
"dateTime": "2017-06-30T07:20:28.606Z",
"totalTime": "2",
"auctionName": "Dxf",
"status": 1,
"id": "5146118144917504",
"kind": "auctionTimeApi#resourcesItem"
},
{
"startTime": "1498806518484",
"endTime": "1498807358484",
"dateTime": "2017-06-30T07:08:38.484Z",
"totalTime": "14",
"auctionName": "rrrtttt",
"status": 1,
"id": "5151952589553664",
"kind": "auctionTimeApi#resourcesItem"
},
{
"startTime": "1498807683483",
"endTime": "1498807863483",
"dateTime": "2017-06-30T07:28:03.483Z",
"totalTime": "3",
"auctionName": "wwew",
"status": 1,
"id": "5956451503702016",
"kind": "auctionTimeApi#resourcesItem"
},
{
"startTime": "1498803576630",
"endTime": "1498803816630",
"dateTime": "2017-06-30T06:19:36.630Z",
"totalTime": "4",
"auctionName": "zzzz",
"status": 0,
"id": "5964732200648704",
"kind": "auctionTimeApi#resourcesItem"
},
{
"startTime": "1498833083854",
"endTime": "1498833563854",
"dateTime": "2017-06-30T14:31:23.854Z",
"totalTime": "8",
"auctionName": "Dartmouth",
"status": 0,
"id": "6314781967384576",
"kind": "auctionTimeApi#resourcesItem"
}
],
"kind": "auctionTimeApi#resources",
"etag": "\"l-71RhD3VMYkQ-s_W643oBlpkCw/1SZlmWzcSB8XxEnhJpjVvwPV5k4\""
}
Above is my JSON data in the Google cloud 
Add This is my SWIFT3 code:
import UIKit
class ViewController: UIViewController , UITableViewDataSource {
#IBOutlet weak var auctionLabel: UILabel!
#IBOutlet weak var auctionTableView: UITableView!
var fetchAuctionName = [AuctionName]()
override func viewDidLoad() {
super.viewDidLoad()
auctionTableView.dataSource = self
parseData()
}
override var prefersStatusBarHidden: Bool {
return true
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchAuctionName.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = auctionTableView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = fetchAuctionName[indexPath.row].auctionname
cell?.detailTextLabel?.text = fetchAuctionName[indexPath.row].auctionname
return cell!
}
func parseData() {
fetchAuctionName = []
let url = "urll"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if (error != nil){
print("Error")
}
else{
do{
let fetchData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
let jsonArray = fetchData.value(forKey: "items") as! NSArray
for eachFetchedAuctionName in jsonArray {
let eachAuctionName = eachFetchedAuctionName as! [String : Any]
let auctionname = eachAuctionName["auctionName"] as! String
self.fetchAuctionName.append(AuctionName(auctionname: auctionname));
}
self.auctionTableView.reloadData()
}
catch{
print("Error 2")
}
}
}
task.resume()
}
}
class AuctionName: NSObject {
var auctionname : String
init(auctionname : String) {
self.auctionname = auctionname
}
}
With this code I can print all the status values from the JSON data
My question is; I just need those with a status value of 0 to be printed. How can I modify my code to achieve this?
Try this
func parseData() {
fetchAuctionName = []
let url = "urlllll"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if (error != nil){
print("Error")
}
else{
do{
let fetchData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
let jsonArray = fetchData.value(forKey: "items") as! NSArray
for eachFetchedAuctionName in jsonArray {
let eachAuctionName = eachFetchedAuctionName as! [String : Any]
let auctionname = eachAuctionName["auctionName"] as! String
if let status = eachAuctionName["staus"] as? Bool{
if status == true{
self.fetchAuctionName.append(AuctionName(auctionname: auctionname));
}
}
}
self.auctionTableView.reloadData()
}
catch{
print("Error 2")
}
}
}
task.resume()
}
}
for eachFetchedAuctionName in jsonArray {
let eachAuctionName = eachFetchedAuctionName as! [String : Any]
let auctionname = eachAuctionName["auctionName"] as! String
self.fetchAuctionName.append(AuctionName(auctionname: auctionname));
// you can typecast to either String or an Int and then compare it respectively
//with a String "1" or an Int(1), whichever suits your app
guard let status = eachAuctionName["status"] as! Int else { return }
if status == 0 {
print("0 found")
}
}
One suggestion: use swift 4 Decodable protocol, to parse JSON easily into custom objects either a struct or a class of your choice, makes the code looks nice and clean.

Parse JSON response using SwiftyJSON iOS

I am trying to parse the following JSON response to get the time and availability for particular date using SwiftyJSON.
I have successfully parsed to get the date from timeSlots.
However, I am unable to get the 'time' of particular date from the response.
{
"statusCode": 200,
"doctorDetailsList": null,
"doctorDetails": {
"id": 219,
"doctorName": "Doris Wunsch",
"qualification": "MD",
"consultationFee": 760,
"experience": 0,
"timeSlots": {
"06/07/2016": [
{
"date": 1465432200000,
"time": "6:00 AM",
"availability": true
},
{
"date": 1465452000000,
"time": "11:30 AM",
"availability": true
}
],
"06/08/2016": [
{
"date": 1465259400000,
"time": "6:00 AM",
"availability": true
},
{
"date": 1465279200000,
"time": "11:30 AM",
"availability": true
}
],
"06/09/2016": [
{
"date": 1465365600000,
"time": "11:30 AM",
"availability": true
}
]
}
},
"totalDoctors": 0,
"message": null
}
This is what I did to get the timeSlots :
let todaysSlots = (self.doctorProfileDetail!["doctorDetails"]["timeSlots"].dictionary?.keys.sort()[0])!
in return, it's giving "06/07/2016".
How do I get time and availability?
Got the result:
let todaysDate = (self.doctorProfileDetail!["doctorDetails"]["timeSlots"]["06/07/2016"])[0]["time"]
let isAvailable = (self.doctorProfileDetail!["doctorDetails"]["timeSlots"]["06/07/2016"])[0]["availability"]
var Data : NSMutableDictionary = NSMutableDictionary()
do {
let path: String = NSBundle.mainBundle().pathForResource("Swift", ofType: "json")!
let url: NSURL = NSURL.fileURLWithPath(path)
let req: NSURLRequest = NSURLRequest(URL: url)
let data: NSData = try NSURLConnection.sendSynchronousRequest(req, returningResponse: nil)
let json: [NSObject : AnyObject] = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [NSObject : AnyObject]
Data = json["doctorDetails"]?.valueForKey("timeSlots") as! NSMutableDictionary
print(Data)
let time : NSMutableDictionary = Data.valueForKey("06/07/2016")?.objectAtIndex(1) as! NSMutableDictionary
let timestring = time.valueForKey("time") as! String
print(timestring)
let availability : NSMutableDictionary = Data.valueForKey("06/07/2016")?.objectAtIndex(1) as! NSMutableDictionary
let numberbool = availability.valueForKey("availability") as! Bool
print(numberbool)
you can use this code and get time and availability enjoy

Resources