Swift: Complex JSON Model data not properly showing in UITableView - ios

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 }

Related

How to separate tableview header and cellForRowAt from same json in swift

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
}

How to implement TextField search bar to filter tableview values Swift

I have created a custom textField bar on top of the ViewController to filter data values in UITableView. As I have a nested type of JSON so couldn't properly get how to use filter for it.
I want to implement textField as a search bar with TableView. screenshot attached.
Value which I need to filter is pickList -> textField
textSearchChange function added for text search.
Data is section wise and then values and is already displaying in tableView.
Model:
struct SectionList : Codable {
let title : String?
var items : [Item]?
}
struct PickListData: Codable {
let items: [Item]?
}
struct Item : Codable {
let actionType : Int?
var textField : String?
var pickList: [SectionList]?
var selection: [Item]?
let selectedValue: [String]?
let version: Int?
let masterId: Int?
let itemValue: String?
}
ViewController Code:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var searchTxt: UITextField!
#IBOutlet weak var tableView: UITableView!
var AppData: Item?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
searchTxt.delegate = self
readDataList()
}
func readDataList(){
if let url = Bundle.main.url(forResource: "list", withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let response = try decoder.decode(PickListData.self, from: data)
let res = response.items?.filter { $0.actionType == 101}
AppData = res?.first
print(AppData)
self.tableView.reloadData()
} catch {
print("error:\(error)")
}
}
}
#IBAction func textSearchChange(_ sender: UITextField) {
print("search")
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return AppData?.pickList?.count ?? 0
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return AppData?.pickList?[section].title
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return AppData?.pickList?[section].items?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let dic = AppData?.pickList?[indexPath.section].items?[indexPath.row]//.pickList?[indexPath.row].title
//AppData?[indexPath.section].pickList[indexPath.row].items
//print(dic)
cell.textLabel?.text = dic?.textField
return cell
}
}
JSON Data:
{
"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"
}
]
}
]
}
]
}
Updated Code: but this is wrong I want to search with TextField
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let searchText = textField.text! + string
Filterdata = (AppData?.pickList?.filter({(($0.title!).localizedCaseInsensitiveContains(searchText))}))!
if(Filterdata.count == 0){
isSearch = false
}else{
isSearch = true
}
self.tableView.reloadData();
return true
}
Image:
Please follow this steps for the working solution
* Step 1 -> Replace struct
struct SectionList : Codable {
let title : String?
var items : [RowItems]?
mutating func filterData(string: String) {
self.items = self.items?.filter({ (item) -> Bool in
if item.textField?.contains(string) == true {
return true
}
return false
})
}
}
struct Item : Codable {
let actionType : Int?
var pickList: [SectionList]?
let version: Int?
mutating func filterData(string: String) {
guard var tempList = pickList else { return }
for index in 0..<tempList.count {
tempList[index].filterData(string: string)
}
pickList = tempList
}
}
* Step 2 -> Create one more variable to hold original data
var globalAppData: Item?
* Step 3 -> Assign value to globalAppData while you parsing json
let res = response.items?.filter { $0.actionType == 101}
AppData = res?.first
globalAppData = AppData
* Step 4 -> Add observer for text change
searchTxt.addTarget(self, action: #selector(textSearchChange(_:)), for: .editingChanged)
* Step 5 -> Replace textDidChange method
#IBAction func textSearchChange(_ sender: UITextField){
var tempData = globalAppData
if let text = sender.text, text.isEmpty == false {
tempData?.filterData(string: text)
}
AppData = tempData
self.tableView.reloadData()
}
* Optional Step 6 ->
If you want case insensitive search then replace this line
item.textField?.contains(string)
with
item.textField?.lowercased().contains(string.lowercased())
//You need to apply action Sent Event is editing changed
#IBAction func actionTextChange(_ sender: UITextField) {
print("get text -----\(sender.text)")
}
In the method textSearchChange
you have the query string sender.text. You should filter the result
and store it to another array. Then you can use the filteredResultArray in the tableView delegate. And every time you modify the filteredResultArray you should reload your tableView.

Parse JSON Using Decodable into TableView Sections with an Array inside an Array

I am attempting to parse data from an api into a tableView with Sections. The end result would be a section title that corresponds with a month and rows with lists of videos that were posted for the month. The videos may not include a poster or description.
I tried to implement a for in loop function to update the model after retrieving the data, which worked great until I started trying to implement sections. I can print the json response to the console and receive the full response.
Here is a sample of the original JSON Structure:
{
"page": {
"type": "videos",
"sections": [{
"title": "September",
"videos": [{
"title": "Some Video",
"description": "Video Description",
"poster": "",
"url": "url"
}]
}, {
"title": "August 2019",
"videos": [{
"title": "Some Video",
"description": "",
"poster": "Some Image",
"url": "url"
}, {
"title": "Some Video",
"description": "No Description",
"poster"",
"url": "url"
}]
}]
}
}
Here is my Model:
struct Root: Decodable {
let page: Page
}
struct Page: Decodable {
let type: String
let sections: [VideoSection]
}
struct VideoSection: Decodable {
let title: String
let videos: [Video]
}
struct Video: Decodable {
let videoTitle: String
let videoDescription: String?
let poster: String?
let url: String
enum CodingKeys: String, CodingKey {
case videoTitle = "title"
case videoDescription = "description"
case poster = "poster"
case url = "url"
}
}
Here is may Networking call with Parsing:
func getVideoData(url: String){
guard let videoUrl = URL(string: "Video_URL") else { return }
URLSession.shared.dataTask(with: videoUrl) { (data, response, error) in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
let responseData = try decoder.decode(Root.self, from: data)
DispatchQueue.main.async {
self.videoTableView.reloadData()
}
} catch let err {
print("Error", err)
}
}.resume()
}
Here is my tableView:
var allvideosArray = [Video]()
var allSectionsArray = [VideoSection]()
var rootArray: Root?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customVideoCell", for: indexPath) as! CustomVideoCell
cell.videoDescriptionPlaceholder.text = Video.CodingKeys.videoDescription.rawValue
cell.videoTitlePlaceholder.text = Video.CodingKeys.videoTitle.rawValue
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return allSectionsArray[section].title
}
func numberOfSections(in tableView: UITableView) -> Int {
return allSectionsArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allvideosArray.count
}
When I attempt to print(responseData.page.sections.videos) I receive the error "Value of type'[VideoSection]' has no member 'videos,' which leads me to believe the issue has to do with the [videos] array inside of the [sections] array.
You can try
var page:Page?
let responseData = try decoder.decode(Root.self, from: data)
self.page = responseData.page
DispatchQueue.main.async {
self.videoTableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customVideoCell", for: indexPath) as! CustomVideoCell
let item = page!.sections[indexPath.section].videos[indexPath.row]
cell.videoDescriptionPlaceholder.text = item.videoDescription
cell.videoTitlePlaceholder.text = item.videoTitle
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return page?.sections[section].title
}
func numberOfSections(in tableView: UITableView) -> Int {
return page?.sections.count ?? 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return page?.sections[section].videos.count ?? 0
}

How to access enum within struct model? Swift

I wanted to display in my tableView the data and time which is within the struct model right now.
I tried accessing view the main, WeatherModel struct but there is a [List] which abandons me accessing the dtTxt. I just want to show the data in every row. Any help would be appreciated. I add my contents below.
Controller:
#IBOutlet var tableView: UITableView!
var weatherData = [WeatherModel]()
override func viewDidLoad() {
super.viewDidLoad()
getJSONData {
self.tableView.reloadData()
}
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return weatherData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
cell.textLabel?.text = weatherData[indexPath.row].city.name.capitalized // Instead of city name, it should be dtTxt.
return cell
}
Here is my model:
struct WeatherModel: Codable {
let list: [List]
let city: City
}
struct City: Codable {
let name: String
}
struct List: Codable {
let main: Main
let weather: [Weather]
let dtTxt: String // I want to show this
enum CodingKeys: String, CodingKey {
case main, weather
case dtTxt = "dt_txt" //access here
}
}
struct Main: Codable {
let temp: Double
}
struct Weather: Codable {
let main, description: String
}
And here is my JSON object:
{
"list": [
{
"main": {
"temp": 277.12
},
"weather": [{
"main": "Clouds",
"description": "scattered clouds"
}],
"dt_txt": "2018-06-05 15:00:00"
},
{
"main": {
"temp": 277.12
},
"weather": [{
"main": "Sunny",
"description": "Clear"
}],
"dt_txt": "2018-06-05 18:00:00"
},
{
"main": {
"temp": 277.12
},
"weather": [{
"main": "Rain",
"description": "light rain"
}],
"dt_txt": "2018-06-05 21:00:00"
}
],
"city": {
"name": "Bishkek"
}
}
[List] contains an array of forecast objects at different times.
Use a for loop:
for forecast in weatherModel.list {
print(forecast.dtTxt)
}
or filter one object by a certain condition:
if let threePMForecast = weatherModel.list.first(where: { $0.contains("15:00") }) {
print(threePMForecast.dtTxt)
}

How can i access value of other Mappble class object.(Alamofire Object Mapper)

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

Resources