not getting table view data after reloading tableview - ios

i am call api using Alamofire and SwiftyJSOn and i am creating model class for display data in tableview here is my response
Response
{
"inspections_todays_data" : [
],
"message" : "Successfully.",
"success" : "1",
"inspections_future_data" : [
],
"inspections_overdue_data" : [
{
"notes" : "Test",
"surveyor_id" : "8",
"longitude" : null,
"time" : "08:00",
"address3" : null,
"county" : "carlow",
"client_id" : "3",
"house_num" : "test street",
"eircode" : "12345",
"address1" : "test area",
"date_inspected" : "2019-01-10",
"address2" : "test city",
"country" : "Ireland",
"latitude" : null,
"name" : "test street",
"property_id" : "22"
}
]
}
as you see in response i have three array and i am fetching inspections_overdue_data array i fetched successfully but not able to display on tableview
Here is my code
Code
func OverdueList(){
let preferences = UserDefaults.standard
let uid = "u_id"
let acTkn = "acc_tkn"
let u_ID = preferences.object(forKey: uid)
let A_Token = preferences.object(forKey: acTkn)
let params = ["user_id": u_ID!, "access_token": A_Token!]
print(params)
Alamofire.request(inspectionsList, method: .post, parameters: params).responseJSON(completionHandler: {(response) in
switch response.result{
case.success(let value):
let json = JSON(value)
print(json)
let data = json["inspections_overdue_data"]
print(data)
if data == []{
self.viewNodata.isHidden = false
}else{
data.array?.forEach({ (iunOverDue) in
let iOveList = OvedueModel(surveyor_id: iunOverDue["surveyor_id"].stringValue, country: iunOverDue["country"].stringValue, time: iunOverDue["time"].stringValue, address2: iunOverDue["address2"].stringValue, notes: iunOverDue["notes"].stringValue, house_num: iunOverDue["house_num"].stringValue, name: iunOverDue["name"].stringValue, address1: iunOverDue["address1"].stringValue, eircode: iunOverDue["eircode"].stringValue, date_inspected: iunOverDue["date_inspected"].stringValue, property_id: iunOverDue["property_id"].stringValue, county: iunOverDue["county"].stringValue, client_id: iunOverDue["client_id"].stringValue)
print(iOveList)
self.overDueData.append(iOveList)
})
self.tblOvedue.reloadData()
}
case.failure(let error):
print(error.localizedDescription)
}
})
}
i also added delegate and datasource through storyboard but still i am not able to show data here is my tableview methods
func numberOfSections(in tableView: UITableView) -> Int {
return 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return overDueData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! OverDueTableViewCell
let name = overDueData[indexPath.row].name
let address1 = overDueData[indexPath.row].address1
cell.lblTitle.text = "\(name) \(address1)"
return cell
}

numberOfSections is returning 0, you have to return at least 1 if you want to see anything.
Protip: If you only have 1 section, you can omit it since 1 is the default return value.

You should either remove below tableview's delegate method or you should return at-least 1.
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

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
}

I want to know why the results are repeated in the table view

I get the value through the php file of the web server.
I hope to bring the results from DB when I search.
There are two problems with my code now.
Spelling that is not included in the values contained in the DB also produces results.
The results come out repeatedly.
First of all, this is the json result I'm getting.
[
{
"name" : "name1",
"id" : "1"
},
{
"name" : "name2",
"id" : "2"
},
{
"name" : "name3",
"id" : "3"
},
{
"name" : "name4",
"id" : "4"
},
{
"name" : "name5",
"id" : "5"
},
{
"name" : "name6",
"id" : "6"
},
{
"name" : "name7",
"id" : "7"
},
{
"name" : "name8",
"id" : "8"
},
{
"name" : "name9",
"id" : "9"
},
{
"name" : "name10",
"id" : "10"
},
{
"name" : "name11",
"id" : "11"
},
{
"name" : "name12",
"id" : "12"
}
]
But in emulators, the results come out this way.
name1
name1
name2
name1
name2
name3
.
.
.
I wonder why the results come out like this.
This is my code.
import UIKit
import Alamofire
import SwiftyJSON
class MyTableViewController: UITableViewController, UISearchBarDelegate {
var arrID = [String]()
var arrName = [String]()
var filteredData = [String]()
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet var mytableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
self.mytableview.delegate = self
self.mytableview.dataSource = self
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return filteredData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
cell.textLabel?.text = filteredData[indexPath.row]
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
let url = "http://url/name.php?name=" + searchText
print(url)
AF.request(url, method: .get).responseJSON { (myresponse) in
switch myresponse.result {
case .success:
let myresult = try? JSON(data: myresponse.data!)
print(myresult!)
let resultArray = myresult!
self.arrID.removeAll()
self.arrName.removeAll()
for i in resultArray.arrayValue {
let id = i["id"].stringValue
self.arrID.append(id)
let name = i["name"].stringValue
self.arrName.append(name)
self.filteredData.append(contentsOf: self.arrName)
}
if searchText == "" {
self.filteredData = []
} else {
for data in self.filteredData {
if data.lowercased().contains(searchText.lowercased()) {
self.filteredData.append(data)
}
}
}
self.mytableview.reloadData()
case .failure:
print(myresponse.error!)
}
}
}
}
You probably want to change this:
for i in resultArray.arrayValue {
let id = i["id"].stringValue
self.arrID.append(id)
let name = i["name"].stringValue
self.arrName.append(name)
self.filteredData.append(contentsOf: self.arrName)
}
To this:
for i in resultArray.arrayValue {
let id = i["id"].stringValue
self.arrID.append(id)
let name = i["name"].stringValue
self.arrName.append(name)
}
self.filteredData.append(contentsOf: self.arrName)
I'm confused why you are doing this, though:
for data in self.filteredData {
if data.lowercased().contains(searchText.lowercased()) {
self.filteredData.append(data)
}
}
Because for each entry in your JSON you add all the data you read so far to your filtered array again. And then you finally add all the entries that contain your search text to filteredArray again.
The first issue will be fixed by removing the line
self.filteredData.append(contentsOf: self.arrName)
from the first loop.
The second loop that does the filtering then needs to be changed to iterate over ˋarrNameˋ instead and you need to clear ˋfilteredDataˋ before.
An even better option would be to use the filter method:
filteredData = arrName.filter { data in
data.lowercased().contains(searchText.lowercased())
}

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

How to filter JSON response in XCODE?

situation:
I have a JSON response parsed via SwiftyJSON. And I'm populating table cells with the data. Everything is cool, but now I need to remove some dictionaries from my JSON, and it doesn't let me do that in an any way (loops or other conditions).
Example of received JSON:
{"post-comments" : [
{
"post" : "new",
"_id" : "1",
},
{
"post" : "new",
"_id" : "2",
},
{
"post" : "post with title",
"_id" : "23",
},
{
"post" : "new",
"_id" : "29",
},
{
"post" : "post with title",
"_id" : "90",
},
{
"post" : "post with title",
"_id" : "33",
}
]
}
I'm tryin to get rid of some dictionaries, lets say if "post" === "new" - I need to remove them from my JSON and continue populate my cells with left data.
Completely stuck.. Any ideas would be much appreciated.
here is the complete tableviewcontroller:
class TableViewContr: UITableViewController {
let Comments : String = "http://localhost:3000/api/comments/"
var json : JSON = JSON.null
override func viewDidLoad() {
super.viewDidLoad()
getPostComments(Comments)
}
func getPostComments(getcomments : String) {
Alamofire.request(.GET, getcomments).responseJSON {
response in
guard let data = response.result.value else {
return
}
self.json = JSON(data)
self.tableView.reloadData()
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch self.json["post-comments"].type {
case Type.Array:
return self.json["post-comments"].count
default:
return 1
}
}
func populateFields(cell: TableViewContrCell, index: Int) {
guard let comment = self.json["post-comments"][index]["post"].string else {
return
}
cell.commentContent!.text = comment
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewContrCell
populateFields(cell, index: indexPath.row)
return cell
}
}
This is an approach to parse and filter the JSON data before reloading the table view.
comments is the data source array containing the post-comments dictionaries
class TableViewContr: UITableViewController {
let commentURL : String = "http://localhost:3000/api/comments/"
var comments = [[String:String]]()
override func viewDidLoad() {
super.viewDidLoad()
getPostComments(commentURL)
}
func getPostComments(getcomments : String) {
Alamofire.request(.GET, getcomments).responseJSON {
response in
guard let data = response.result.value else { return }
let jsonData = JSON(data)
let postComments = jsonData["post-comments"].arrayObject as! [[String:String]]
self.comments = postComments.filter{$0["post"] != "new"}
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewContrCell
let comment = comments[indexPath.row]
cell.commentContent!.text = comment["post"]!
return cell
}
}

Resources