Related
I want to display countrycode as header of table view and after click on header venue should display. I had tried but I'm unable to achieve output as expected.
This is my json :
{
"meetings": [
{
"meetingId": 31389393,
"name": "Ludlow 20th Apr",
"openDate": "2022-04-20T12:00:00+00:00",
"venue": "Ludlow",
"eventTypeId": 7,
"countryCode": "GB",
"meetingGoing": "Good"
},
{
"meetingId": 31389469,
"name": "Catterick 20th Apr",
"openDate": "2022-04-20T12:40:00+00:00",
"venue": "Catterick",
"eventTypeId": 7,
"countryCode": "GB",
"meetingGoing": "Good (Good to Soft in places)"
},
{
"meetingId": 31389416,
"name": "Perth 20th Apr",
"openDate": "2022-04-20T12:50:00+00:00",
"venue": "Perth",
"eventTypeId": 7,
"countryCode": "GB",
"meetingGoing": "Good to Soft (Good in places)"
},
{
"meetingId": 31389532,
"name": "Lingfield 20th Apr",
"openDate": "2022-04-20T15:15:00+00:00",
"venue": "Lingfield",
"eventTypeId": 7,
"countryCode": "GB",
"meetingGoing": "Standard"
},
{
"meetingId": 31389447,
"name": "Salisbury 20th Apr",
"openDate": "2022-04-20T15:25:00+00:00",
"venue": "Salisbury",
"eventTypeId": 7,
"countryCode": "GB",
"meetingGoing": "Good to Firm (Good in places)"
}
]
}
Here is my code which is I'm using for getting data:
struct Racing{
var countryCode:String
var venue: [String]
var races: [Races]?
}
var todayRacingArray = [Racing]()
APIClient2<RacingListBaseClass>().API_GET(Url: url, Params: noParams, Authentication: false, Progress: false, Alert: true, Offline: false, SuperVC: self, completionSuccess: { (response) in
for item in response.meetings ?? []
{
let cc = item.countryCode
var venue = [String]()
ven.append(item.venue ?? "")
let obj = Racing(countryCode: cc ?? "", venue: venue)
self.todayRacingArray.append(obj)
}
self.otherSportsTableView.reloadData()
}) { (failed) in
}
TableView:
func numberOfSections(in tableView: UITableView) -> Int {
return self.todayRacingArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.todayRacingArray[section].venue.count
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: HeaderTableViewCell.self)) as! HeaderTableViewCell
let obj = todayRacingArray[section]
cell.titleLbl.text = obj.countryCode
return cell
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: BodyTableViewCell.self)) as! BodyTableViewCell
cell.frame = tableView.bounds
cell.layoutIfNeeded()
let obj = self.todayRacingArray[indexPath.section].venue[indexPath.row]
cell.horseTitleLabel.text = obj
return cell
}
My Output My table Header After Clicking on header
I want Output like this: enter image description here After clicking on header
Please someone helpme out with this.
Updated Answer
Add a new model RaceVenue. Then modify Racing struct like below.
struct RaceVanue {
var venue: String
var races: [Race]?
}
struct Racing {
var countryCode:String
var raceVenues: [RaceVanue]
}
Modify the declaration of countryVenueDict dictionary.
var countryVenueDict: [String: [RaceVanue]] = [:]
Then modify the code when adding it to countryVenueDict dictionary. And then also modify Racing model when add it to todayRacingArray
for item in response.meetings ?? []
{
if let _ = countryVenueDict[item.countryCode ?? ""] {
countryVenueDict[item.countryCode ?? ""]?.append(RaceVanue(venue: item.venue ?? "", races: item.races))
} else {
countryVenueDict[item.countryCode ?? ""] = [RaceVanue(venue: item.venue ?? "", races: item.races)]
}
}
todayRacingArray += countryVenueDict.map { Racing(countryCode: $0.key, raceVenues: $0.value) }
Previous Answer
Add a dictionary to map the venue with countrycode before the declaration of todayRacingArray
var countryVenueDict: [String: [String]] = [:]
var todayRacingArray = [Racing]()
Modify the code in for loop like below.
for item in response.meetings ?? []
{
if let _ = countryVenueDict[item.countryCode ?? ""] {
countryVenueDict[item.countryCode ?? ""]?.append(item.venue ?? "")
} else {
countryVenueDict[item.countryCode ?? ""] = [item.venue ?? ""]
}
}
Then append [Racing] array to todayRacingArray by mapping the transforming the countryVenueDict by using map function.
todayRacingArray += countryVenueDict.map { Racing(countryCode: $0.key, venue: $0.value) }
Here is the full code
var countryVenueDict: [String: [String]] = [:]
var todayRacingArray = [Racing]()
APIClient2<RacingListBaseClass>().API_GET(Url: url, Params: noParams, Authentication: false, Progress: false, Alert: true, Offline: false, SuperVC: self, completionSuccess: { (response) in
for item in response.meetings ?? []
{
if let _ = countryVenueDict[item.countryCode ?? ""] {
countryVenueDict[item.countryCode ?? ""]?.append(item.venue ?? "")
} else {
countryVenueDict[item.countryCode ?? ""] = [item.venue ?? ""]
}
}
todayRacingArray += countryVenueDict.map { Racing(countryCode: $0.key, venue: $0.value) }
self.otherSportsTableView.reloadData()
}) { (failed) in
}
I have a complex JSON (nested values) in it, I properly implemented and data values are in model. But for some unknown reasons its not printing complete data only showing me first 12 values and actually it has 71 data values.
I know I am doing something wrong in adjusting indexPath because of complex data. My model and json are complex(nested) and iterations one.
I need to show tableView data which has specific only like - action type actionType": 101 and title as section in picklist(check json) and textField values in tableView list.
So how can I properly set AppData?.items?[indexPath.row] this for section and for row.
Note: I only need one action type from JSON which is 101 and Title as a tableView Section and textField as list values and these both in pickList. I attached sample small JSON.
Code:
var AppData: SectionList?
let decoder = JSONDecoder()
let response = try decoder.decode(SectionList.self, from: pickResult)
self.AppData = response
TableView:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return AppData?.items?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let dic = AppData?.items?[indexPath.row].actionType
return cell
}
Model:
struct SectionList : Codable {
let title : String?
var items : [Item]?
var modified: Bool? = false
}
struct Item : Codable {
let actionType : Int?
let actionUrl : String?
let bgColor : String?
let booleanValue : Bool?
var textField : String?
var textValue : String?
let unitId : Int?
let latitude : Double?
let longitude : Double?
let actionParamData: String?
let actionTitle: String?
let pickList: [SectionList]?
var selection: [Item]?
let multiSelect: Bool?
let selectedValue: [String]?
let version: Int?
let masterId: Int?
let actionId: Int?
let itemValue: String?
var required: Bool? = false
}
Sample JSON:
{
"items": [
{
"actionType": 101,
"version": 3,
"pickList": [
{
"title": "Sayaç yeri seçimi",
"items": [
{
"textField": "Sayaç Yeri Seçiniz",
"itemValue": "0"
},
{
"textField": "Sayaç daire girişinde",
"itemValue": "1"
},
{
"textField": "Sayaç apt. girişinde",
"itemValue": "2"
},
{
"textField": "Sayaç bodrumda",
"itemValue": "3"
},
{
"textField": "Sayaç çatı katında",
"itemValue": "4"
},
{
"textField": "Sayaç bahçede (Müstakil)",
"itemValue": "5"
},
{
"textField": "Sayaç bina dışında",
"itemValue": "6"
},
{
"textField": "Sayaç balkonda",
"itemValue": "7"
},
{
"textField": "Sayaç daire içinde",
"itemValue": "8"
},
{
"textField": "Sayaç istasyon içinde",
"itemValue": "9"
}
]
}
]
},
{
"actionType": 1015,
"version": 3,
"pickList": [
{
"title": "AĞAÇ KURUTMA ÜNİTESİ",
"items": [
]
}
]
},
{
"actionType": 1016,
"version": 3,
"pickList": [
{
"title": "ASTAR FIRINI",
"items": [
]
}
]
}
]
}
Updated Code
var AppData: [Inner]?
let decoder = JSONDecoder()
let response = try decoder.decode(Root.self, from: pickResult)
let res = response.items.filter { $0.actionType == 103 }
self.AppData = res
func numberOfSections(in tableView: UITableView) -> Int {
return AppData?.count ?? 0
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return AppData?[section].pickList[section].title
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return AppData?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let dic = AppData?[indexPath.section].pickList[indexPath.row].items
print(dic)
let data = dic?[indexPath.row].textField
cell.textLabel?.text = data
return cell
}
You need
struct Root: Codable {
let items: [Inner]
}
struct Inner: Codable {
let actionType, version: Int
let pickList: [PickList]
}
struct PickList: Codable {
let title: String
let items: [PickListItem]
}
struct PickListItem: Codable {
let textField, itemValue: String
}
let decoder = JSONDecoder()
let response = try decoder.decode(Root.self, from: pickResult)
let res = response.items.filter { $0.actionType = 101 }
Server response:
{
"success": {
"allDishes": [
{
"_id": "5dd78586c2f2871d84061929",
"dishType": "non_veg",
"recommended": true,
"isCustomizable": false,
"isAddons": false,
"availability": true,
"restaurantId": "5dad401b52c8ff200caf41da",
"categoryId": "5dc553ffd7b692257cebd170",
"categoryName": "north indian",
"subcategoryId": "5dc556ebcf881d19f4369f77",
"subcategoryName": "subtest",
"name": "Hand Fry",
"price": 100,
"dishImage": "/images/dish/1574405510680-1574405429836.jpg",
"customizable": [],
"addons": []
},
{
"_id": "5df9da5bc20d011e7c394f36",
"dishType": "veg",
"recommended": true,
"isCustomizable": true,
"isAddons": true,
"availability": true,
"restaurantId": "5dad401b52c8ff200caf41da",
"categoryId": "5dc553ffd7b692257cebd170",
"categoryName": "north indian",
"subcategoryId": "5dc556ebcf881d19f4369f77",
"subcategoryName": "subtest",
"name": "Rajdeep Special",
"price": 130,
"dishImage": "/images/dish/1576655451745-1576655324988.jpg",
"customizable": [
{
"_id": "5df9da5bc20d011e7c394f38",
"price": 20,
"title": "250 GM"
},
{
"_id": "5df9da5bc20d011e7c394f37",
"price": 35,
"title": "500 GM"
}
],
"addons": [
{
"_id": "5df9da5bc20d011e7c394f3a",
"price": 10,
"title": "Ice"
},
{
"_id": "5df9da5bc20d011e7c394f39",
"price": 30,
"title": "Tea"
}
]
},
{
"_id": "5df725448b8247182080ec47",
"dishType": "non_veg",
"recommended": false,
"isCustomizable": false,
"isAddons": false,
"availability": false,
"restaurantId": "5dad401b52c8ff200caf41da",
"categoryId": "5dc68d68ab42841948a56dd5",
"categoryName": "chinese",
"subcategoryId": "",
"subcategoryName": "",
"name": "This Is Or",
"price": 20,
"dishImage": "/images/dish/1576478019834-1576477996438.jpg",
"customizable": [],
"addons": []
},
{
"_id": "5df7233dbac9d01b3022f846",
"dishType": "veg",
"recommended": true,
"isCustomizable": false,
"isAddons": false,
"availability": true,
"restaurantId": "5dad401b52c8ff200caf41da",
"categoryId": "5dc8fa090535a7112c7b8cd4",
"categoryName": "sweets",
"subcategoryId": "5dcbd3268a276d0accc4cc75",
"subcategoryName": "laddu",
"name": "laddu n",
"price": 30,
"dishImage": "/images/dish/1576477501434-1576477479394.jpg",
"customizable": [],
"addons": []
},
{
"_id": "5df777d6ac1fc41844eaa2e3",
"dishType": "veg",
"recommended": false,
"isCustomizable": false,
"isAddons": false,
"availability": true,
"restaurantId": "5dad401b52c8ff200caf41da",
"categoryId": "5dc8fa090535a7112c7b8cd4",
"categoryName": "sweets",
"subcategoryId": "5dcbd3268a276d0accc4cc75",
"subcategoryName": "laddu",
"name": "laddu Wala ",
"price": 30,
"dishImage": "/images/dish/1576499158059-1576499116976.jpg",
"customizable": [],
"addons": []
},
{
"_id": "5df721df466f951b044d588f",
"dishType": "veg",
"recommended": true,
"isCustomizable": false,
"isAddons": false,
"availability": false,
"restaurantId": "5dad401b52c8ff200caf41da",
"categoryId": "5dc8fa090535a7112c7b8cd4",
"categoryName": "sweets",
"subcategoryId": "5dce9db6a1b36c03e019c22f",
"subcategoryName": "milk cake",
"name": "Milk ",
"price": 30,
"dishImage": "/images/dish/1576477151887-1576477133177.jpg",
"customizable": [],
"addons": []
}
],
"restaurentData": {
"_id": "5dad401b52c8ff200caf41da",
"name": "Trump Restaurant",
"firmName": "Tramp",
"email": "eggwalas#gmail.com",
"phoneNo": "8282828282",
"address": "Jaipur",
"profile_pic": "/images/restaurant/profile/1572937985224-1572937977064.jpg",
"lat": 26.852755861231476,
"long": 75.80524798482656,
"fssai": "1234567891"
}
}
}
code i did:
extension ResturantController : UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return categoryNameArr.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?{
return categoryNameArr[section]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allDishArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let data = self.allDishArray[indexPath.row] as! NSDictionary
let cell = tableView.dequeueReusableCell(withIdentifier: "DishListCell", for: indexPath) as! DishListCell
for i in 0..<categoryNameArr.count {
let catName = categoryNameArr[i]
print("categoryNameToFind :: ",catName)
for j in 0..<allDishArray.count {
let dishes = self.allDishArray[j] as! NSDictionary
if let catNameFound = dishes.value(forKey: "categoryName") as? String{
//print("catNameFound :: ",catNameFound)
if catNameFound == catName {
print("Category Found")
}
}
}
}
if let dishType = data.value(forKey: "dishType") as? String{
if dishType == "veg"{
cell.imgVegNonVeg.image = UIImage(named: "veg")
}else if dishType == "non_veg"{
cell.imgVegNonVeg.image = UIImage(named: "non-veg")
}else{
cell.imgVegNonVeg.isHidden = true
}
}else{
cell.imgVegNonVeg.isHidden = true
}
if let dishName = data.value(forKey: "name") as? String{
cell.lblDishName.text = dishName
}else{
cell.lblDishName.text = "NO DATA"
}
if let price = data.value(forKey: "price") as? Int{
cell.lblDishPrice.text = "₹ " + String (price)
}else{
cell.lblDishPrice.text = "NO DATA"
}
return cell
}
}
Want to display data as appears in this screen shot attached
I tried:
1) Make a new array with all categories and the removed the duplicate entries from it, at last I have 3 array ["north indian","chinese","sweets"]
2) not how to stucked at how to show data in a cell specific to its header.
Tap this link for server response: Server response
First of all parse your JSON with Codable. You can use the below models to parse your data.
struct Root: Decodable {
let allDishes: [Dish]
let restaurentData: Restaurant
enum CodingKeys: String, CodingKey {
case success, allDishes, restaurentData
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let success = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .success)
allDishes = try success.decode([Dish].self, forKey: .allDishes)
restaurentData = try success.decode(Restaurant.self, forKey: .restaurentData)
}
}
struct Dish: Decodable {
let categoryName: String
let price: Double
let name: String
}
struct Restaurant: Decodable {
let name: String
}
In the above models, I've only added some properties. You can add whatever properties you want to parse from the JSON.
Now, in your ViewController create a variable allDishesArr that will be used as the dataSource of your tableView.
var allDishesArr = [(String, [Dish])]()
Next, parse your JSON using above created models and save the response in allDishesArr. Use Dictionary's init(grouping:by:) to group the dishes based in categoryName and then modify the response using map(_:) like so,
do {
let response = try JSONDecoder().decode(Root.self, from: data)
self.allDishesArr = Dictionary(grouping: response.allDishes) { $0.categoryName }.map({ ($0.key, $0.value) })
} catch {
print(error)
}
At last, your UITableViewDataSource methods goes like,
func numberOfSections(in tableView: UITableView) -> Int {
return allDishesArr.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allDishesArr[section].1.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DishListCell", for: indexPath) as! DishListCell
let dish = allDishesArr[indexPath.section].1[indexPath.row]
cell.lblDishName.text = dish.name
//add rest of the code
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let categoryName = allDishesArr[section].0
return categoryName
}
So here is the JSON
{
"city": {
"id": 4930956,
"name": "Boston",
"coord": {
"lon": -71.059769,
"lat": 42.358429
},
"country": "US",
"population": 0,
"sys": {
"population": 0
}
},
"cod": "200",
"message": 0.0424,
"cnt": 39,
"list": [
{
"dt": 1473476400,
"main": {
"temp": 76.33,
"temp_min": 73.11,
"temp_max": 76.33,
"pressure": 1026.47,
"sea_level": 1027.96,
"grnd_level": 1026.47,
"humidity": 73,
"temp_kf": 1.79
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
],
"clouds": {
"all": 8
},
"wind": {
"speed": 7.29,
"deg": 300.501
},
Here is my Controller where I go grab the data......
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var amConnected: UILabel!
#IBOutlet weak var weatherTable: UITableView!
var arrRes = [[String:AnyObject]]()
var swiftyJsonVar: JSON?
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.doSomethingNotification(_:)), name: "ReachabilityChangedNotification", object: nil)
let openWMAPI = "http://api.openweathermap.org/data/2.5/forecast/city?q=Boston,Ma&APPID=XXXXXXXXXXXXXXX&units=imperial"
Alamofire.request(.GET,openWMAPI).responseJSON{
(responseData) -> Void in
print(responseData)
let swiftyJsonVar = JSON(responseData.result.value!)
self.weatherTable.reloadData()
}
.responseString{ response in
//print(response.data.value)
// print(response.result.value)
//print(response.result.error)
//eprint("inhere");
}
weatherTable.rowHeight = UITableViewAutomaticDimension
weatherTable.estimatedRowHeight = 140
// Do any additional setup after loading the view, typically from a nib.
}
In my table loop it is now saying that the jsonArray is nil and failing.
I'm unsure as to what I'm doing wrong at this point.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = weatherTable.dequeueReusableCellWithIdentifier("theCell", forIndexPath: indexPath)
let label1 = cell.viewWithTag(101) as! UILabel
print("inhere")
if((swiftyJsonVar) != nil){
if let jsonArray = self.swiftyJsonVar["list"].array {
var temp = jsonArray[indexPath.row]["main"]["temp"].float
var rdate = jsonArray[indexPath.row]["dt_txt"].string
print(temp)
}else{
print("test")
}
}
label1.text = "TEST"
return cell
}
OVerall I'm just not sure how to dig down into the next level of the JSON.
If you are not averse to it, try using AlamofireObjectMapper instead of SwiftyJson
1) If you are going to change the name of the json keys very often, and are going to do a lot of enum transformations try :
AlamofireObjectMapper
2) If the names are going to be the same, with minimal transformations, directly use :
AlamofireJsonToObjects
Both of these cases, create model classes for your json object. If you have an array - you can define a var as an array
if it is an object or an array of objects - you can then create another model class which is again Mappable and then define such an object var in the original model.
The above libraries will make your code extremely clean while extracting objects to json.
You can access to the elements inside an JSON array in SwiftyJSON using consecutive subscripts, if we have the following JSON for example:
var json: JSON = ["name": "Jack", "age": 25,
"list": ["a", "b", "c", ["what": "this"]]]
Then you can access to the four element of the subarray listcontained in the main array in the following way for example:
json["list"][3]["what"] // this
Or you can define a path like this let path = ["list",3,"what"] and then call it in this way:
json[path] // this
With the above explained let's introduce it with your JSON file to list the elements inside the array weather:
if let jsonArray = json["list"].array {
// get the weather array
if let weatherArray = jsonArray[0]["weather"].array {
// iterate over the elements of the weather array
for index in 0..<weatherArray.count {
// and then access to the elements inside the weather array using optional getters.
if let id = weatherArray[index]["id"].int, let main = weatherArray[index]["main"].string {
print("Id: \(id)")
print("Main: \(main)")
}
}
}
}
And you should see in the console:
Id: 800
Main: Clear
I hope this help you.
in my app i am first time using AlamofireObjectMapper.
So i am mapping api response data in one class and then i want to use that data.
So here is my code that how i map object
extension OrderListViewController
{
func get_order_list()
{
let url = "\(OrderURL)get_New_order_byPharmacy"
let param : [String : AnyObject] = [
"pharmacyId" : "131"
]
Alamofire.request(.GET, url, parameters: param, encoding: .URL).responseObject { (response:Response<OrderList, NSError>) in
let OrderList = response.result.value
print(OrderList!.Message)
}
}
}
and here is the class where i saving my data
class OrderList: Mappable {
var Message : String!
var Status : Int!
var result:[OrderResult]?
required init?(_ map: Map){
}
func mapping(map: Map) {
Message <- map["Message"]
Status <- map["Status"]
result <- map["Result"]
}
}
now in my OrderListViewController i want to use this data so how can i use this??
class OrderListViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var table_OrderList: UITableView!
override func viewDidLoad() {
slideMenuController()?.addLeftBarButtonWithImage(UIImage(named: "ic_menu_black_24dp")!)
slideMenuController()?.addRightBarButtonWithImage(UIImage(named: "ic_notifications_black_24dp")!)
get_order_list()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : OrderList_Cell = tableView.dequeueReusableCellWithIdentifier("OrderList_Cell") as! OrderList_Cell
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
}
for example i want to print message value in my tableview cell label. so how can i get that value form OrderList?
Thanks slava its give me some solution. but my json response give me array. So how can i manage it? and i want to return in numberofrowinSetcion is count of array so how can i do this. please see my updated question.
here is my api response.
{
"Status": 1,
"Message": "records are available",
"Result": [
{
"id": 30162,
"status_id": 2,
"status_type": "New Order",
"created_date": "2016-05-11T10:45:00.6779848",
"created": "11 May 2016"
},
{
"id": 30170,
"status_id": 2,
"status_type": "New Order",
"created_date": "2016-05-12T07:01:00.6968385",
"created": "12 May 2016"
},
{
"id": 30171,
"status_id": 2,
"status_type": "New Order",
"created_date": "2016-05-12T09:12:53.5538349",
"created": "12 May 2016"
},
{
"id": 30172,
"status_id": 2,
"status_type": "New Order",
"created_date": "2016-05-12T09:46:09.4329398",
"created": "12 May 2016"
},
{
"id": 30173,
"status_id": 2,
"status_type": "New Order",
"created_date": "2016-05-12T11:26:58.3211678",
"created": "12 May 2016"
},
{
"id": 30178,
"status_id": 2,
"status_type": "New Order",
"created_date": "2016-05-16T07:34:19.9128517",
"created": "16 May 2016"
}
]
}
You need a local variable in your controller to store all the received information that will be used to fill the table. Something like that should do:
class OrderListViewController: ... {
private var orderList: OrderList? // <- the local variable needed
...
}
extension OrderListViewController {
func get_order_list() {
...
Alamofire
.request(...)
.responseObject { (response:Response<OrderList, NSError>) in
switch response.result {
case .Success(let value):
self.orderList = value // <- fill the local variable with the loaded data
self.tableView.reloadData()
case .Failure(let error):
// handle error
}
}
}
...
}
extension OrderListViewController: UITableViewDataSource {
...
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : OrderList_Cell = tableView.dequeueReusableCellWithIdentifier("OrderList_Cell") as! OrderList_Cell
// I assume 'OrderList_Cell' class has outlet for status type named 'statusTypeLabel' and OrderResult.statusType is of type String
if let orderList = orderList, orderResults = orderList.result {
cell.statusTypeLabel.text = orderResults[indexPath.row].statusType // <- use of the locally stored data
}
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let orderList = orderList, orderResults = orderList.result {
return orderResults.count
} else {
return 0
}
}
}
Note: the code should be correct in case you receive the single object in JSON from backend.
If backend sends the array of objects - you'll need to use array to store local data (private var listOfOrderLists: [OrderList]) and use Alamofire.request(...).responseArray(...) instead. But the idea about local variable is still the same.
typealias FailureHandler = (error: AnyObject) -> Void
typealias SuccessHandler = (result: AnyObject) -> Void
class WebServiceManager: NSObject {
class func getDataFromService(mehodName:String,success:(result:AnyObject)->(), apiError:(FailureHandler))
{
let url = "\(OrderURL)get_New_order_byPharmacy"
let param : [String : AnyObject] = [
"pharmacyId" : "131"
]
alamoFireManager!.request(.GET, url)
.responseJSON { response in
print(response.response!)
print(response.result)
CommonFunctions.sharedInstance.deactivateLoader()
switch response.result {
case .Success(let JSON):
print("Success with JSON: \(JSON)")
guard let _ = JSON as? NSMutableArray else {
apiError(error: "")
return
}
let listOfItem:NSMutableArray = NSMutableArray()
for (_, element) in adsArray.enumerate() {
let adsItem = Mapper<OrderList>().map(element)
listOfItem.addObject(adsItem!)
}
success(result:listOfItem)
case .Failure(let data):
print(data)
}
}
}
class OrderListViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var table_OrderList: UITableView!
var listOFOrder:NSMutableArray =[]
override func viewDidLoad() {
slideMenuController()?.addLeftBarButtonWithImage(UIImage(named: "ic_menu_black_24dp")!)
slideMenuController()?.addRightBarButtonWithImage(UIImage(named: "ic_notifications_black_24dp")!)
WebServiceManager.getDataFromService("", success: { (result) in
listOFOrder = result as NSMutableArray
self.recordTable?.reloadData()
}) { (error) in
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : OrderList_Cell = tableView.dequeueReusableCellWithIdentifier("OrderList_Cell") as! OrderList_Cell
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listOFOrder.count
}
}