I need to create a tableview and fill that with database information that I take with json. This is the response I get from the database with json
{
"news": [
{
"id": "35",
"type": "news",
"title": "final test for offer",
"city": "Mumbai",
"description": "Test description",
"image": "http://www.saimobileapp.com/mobileappbackend/news/IMG_0421.JPG"
},
{
"id": "31",
"type": "news",
"title": "new test",
"city": "Mumbai",
"description": "yes its a test msg",
"image": "http://www.saimobileapp.com/mobileappbackend/news/Chrysanthemum.jpg"
},
{
"id": "30",
"type": "news",
"title": "This is a test news",
"city": "Mumbai",
"description": "Test description",
"image": "http://www.saimobileapp.com/mobileappbackend/news/1.jpg"
}
]
}
These are 3 different news with title etc., so I need to count it as I will add new, and create a table view in base of that.
This is my code now to get the database information with new EDIT:
func LoadNews() {
let post:NSString = ""
NSLog("PostData: %#",post);
let url:NSURL = NSURL(string: "http://saimobileapp.com/services/sai_news.php")!
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
let responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %#", responseData);
var error: NSError?
var Title: [String] = []
if let jsonData = NSJSONSerialization.JSONObjectWithData(urlData!, options: nil, error: &error) as? [String:AnyObject] { // dictionary
if let locationsArray = jsonData["news"] as? [[String:AnyObject]] { // array of dictionaries
for locationDictionary in locationsArray { // we loop in the array of dictionaries
if let location = locationDictionary["title"] as? String { // finally, access the dictionary like you were trying to do
Title.append(location)
var SaveTitle = save.setObject(Title, forKey: "NewsTitle")
}
}
}
}
}
}
}
And for TableView i use that now :
// MARK: UITextFieldDelegate Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var FormName = save.arrayForKey("NewsTitle")!
return FormName.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var FormName = save.arrayForKey("NewsTitle")!
var cell:UITableViewCell = self.TableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
let row = indexPath.row
cell.textLabel?.text = FormName[indexPath.row] as! String
if (indexPath.row % 2 == 0) {
cell.backgroundColor = UIColor.clearColor()
}else{
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.0)
}
cell.textLabel?.textColor = UIColor.whiteColor()
return cell
}
// MARK: UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
TableView.deselectRowAtIndexPath(indexPath, animated: false)
let row = indexPath.row
How can i show the description in the second page when i tap on the cell?
Can anyone please help me? Thanks in advance.
Follow these steps to render your table view:
Assuming you have set your view controller as datasource and delegate for UITableViewController.
In your table view controller' subclass: inside loadView or viewWillAppear make server call to fetch the details. [This you might already be doing]
Create a global parameter to hold to that data. e.g. self.vehicles = jsonData["news"]
After server response, call reloadDatamethod on self.tableView. This will trigger calls to your table data sources methods - numberOfRowsInSection:, cellForRowAtIndexPath: etc.
Return correct values from data source methods. Based on your needs you can create a custom cell and use self.vehicles to fetch & render data on it.
Edit:
Example
Your data is a array of dictionary where array count will drive the number of cells in the table. That said, lets say there are 5 dictionaries in your array so you have 5 cells. When you get a call on cellForRowAtIndexPath:, use 'index path.row' to get the right dictionary mapped to the cell in request. Now, fetch the values inside that dictionary and set them on cell. Like this:
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
// Configure the cell...
let cellId: NSString = "Cell"
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellId) as UITableViewCell
if let ip = indexPath {
var data = self.vehicles[ip.row] as NSDictionary
cell.textLabel.text = data.valueForKey("title") as String
}
return cell
}
Similarly implement didSelectRowAtIndexPath and then fetch & pass on description to your target view controller for display.
Edit 2 (On OP request):
Based on second screen design (table controller or simple view controller), create a new controller class. Then, as I mentioned above, implement didSelectRowAtIndexPath something like below:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var description = String()
if let ip = indexPath {
var data = self.vehicles[ip.row] as NSDictionary
description = data.valueForKey("description") as String
}
var descriptionVC = SecondScreenVC(withDescription: description)
self.navigationController.pushViewController(descriptionVC, animated: true)
}
Some references:
Apple Docs on UITableViewController
Handling UITableViewController Programmatically
The object of key news is an Array (of dictionaries), not a Dictionary
if let vehicles = jsonData["news"] as? NSArray {
for vehicle in vehicles {
let vehiclesKeys = vehicle.allKeys
println(vehiclesKeys)
println("123")
}
}
}
vehicles.count gives you the number of items in the array.
Related
How can I check if all rows in a tableview contain an checkmark accessory? I currently have a tableview that has checkmarks that appear if the user selects on the row. Checkmarks also appear on tableview once the TableViewController loads and JSON criteria is met for example
Can allSatisfy be used to check if checkbox = 1 for all records in the array?
JSON Decodable Structure:
struct JSONStruct: Decodable {
let code: String
var checkbox: Int
var isSelected : Bool {
get { return checkbox == 1 }
set { checkbox = newValue ? 1 : 0 }
}
enum CodingKeys : String, CodingKey {
case code, checkbox
}
}
cellForRowAt:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let item = structure[indexPath.row]
cell.accessoryType = item.isSelected ? .checkmark : .none
Once a button is pressed I would like to display an error if all rows in the tableview do not have an accessory type checkmark. How can I check for this?
var structure = [JSONStruct]()
private func fetch() {
guard let url = URL(string: "\(BaseURL.url)records.php"),
else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = "page=\(var1)".data(using: .utf8)
URLSession.shared.dataTask(with: request) { data, _, error in
guard let data = data else { return }
do {
self.structure = try JSONDecoder().decode([JSONStruct].self,from:data)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch {
print(error)
}
}.resume()
}
Response example:
[
{
"code": "2423343",
"checkbox": 0
},
{
"code": "0902392",
"checkbox": 1
},
]
How can allSatisfy be used to identify if checkbox equals 1 for all records in array?
My app retrieves json from the newsAPI.com . When I look at the json returned from the web service , it shows 2000 values however it returns 20 values loaded into my tableview controller. How do I increase the value so that when the user scrolls down the table view, they are presented with more values loaded into the table view controller?
class LatestNewsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let newsData = Articles() //Model object
let urlRequest = "https://newsapi.org/v2/everything?q=coronavirus&apiKey=d32071cd286c4f6b9c689527fc195b03" //Website API
var urlSelected = ""
var articles: [Articles]? = [] // holds array of Articles data
var indexOfPageToRequest = 1
#IBOutlet weak var table_view: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
table_view.cellLayoutMarginsFollowReadableWidth = true
navigationController?.navigationBar.prefersLargeTitles = true
retriveData( )
}
func retriveData( )->Int{
guard let aritcleUrl = URL(string: urlRequest) else { //send a request to the server
return n
}
let request = URLRequest(url: aritcleUrl)
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) -> Void in //collects content from website
if error != nil { // checks if content is available
print(error ?? 0)
return
}
if let data = data { // converts data to an array of Article objects
self.articles = self.parseData(data: data)
}
})
task.resume()
return n
}
func parseData(data:Data)-> [Articles] {
var articles: [Articles]? = [] // holds parsed data
do {
let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
let jsonArticles = jsonResult?["articles"] as? [AnyObject] ?? [] // gets first head of json file and converts it to dictionary
for jsonArticle in jsonArticles{ // captures data and stores it in the model object
let article = Articles()
article.author = jsonArticle["author"] as? String
article.title = jsonArticle["description"] as? String
article.publishedAt = jsonArticle["publishedAt"] as? String
article.urlImage = jsonArticle["urlToImage"] as? String
article.urlWebsite = jsonArticle["url"] as? String
articles?.append(article) //put article data in the array
}
print(jsonArticles)
DispatchQueue.main.async {
if(articles!.count > 0)
{
self.table_view.reloadData()
}
}
} catch {
print("Nothing my guy\(error)")
}
return articles ?? [] // returns an array of articles
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return articles?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! NewsTableViewCell
cell.authorName.text = articles?[indexPath.row].author
cell.headLine.text = articles?[indexPath.row].title
cell.newsImage.downloadImage(from:(self.articles?[indexPath.item].urlImage ?? "nill"))
cell.timePublication.text = articles?[indexPath.row].publishedAt
return cell
}
[1]: https://i.stack.imgur.com/OY5G5.png
First, I would check the constraints of the table view, because this is a common issue (usually 0,0,0,0)
And also I would check the 'scrolling enabled' in the Attribute inspector and 'reuse Identifier'
Essentially I have am using JSON data to create an array and form a tableview.
I would like the table cells to be grouped by one of the fields from the JSON array.
This is what the JSON data looks like:
[{"customer":"Customer1","number":"122039120},{"customer":"Customer2","number":"213121423"}]
Each number needs to be grouped by each customer.
How can this be done?
This is how I've implemented the JSON data using the table:
CustomerViewController.swift
import UIKit
class CustomerViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, FeedCustomerProtocol {
var feedItems: NSArray = NSArray()
var selectedStock : StockCustomer = StockCustomer()
let tableView = UITableView()
#IBOutlet weak var customerItemsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//set delegates and initialize FeedModel
self.tableView.allowsMultipleSelection = true
self.tableView.allowsMultipleSelectionDuringEditing = true
self.customerItemsTableView.delegate = self
self.customerItemsTableView.dataSource = self
let feedCustomer = FeedCustomer()
feedCustomer.delegate = self
feedCustomer.downloadItems()
}
}
func itemsDownloaded(items: NSArray) {
feedItems = items
self.customerItemsTableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of feed items
print("item feed loaded")
return feedItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Retrieve cell
let cell = tableView.dequeueReusableCell(withIdentifier: "customerGoods", for: indexPath) as? CheckableTableViewCell
let cellIdentifier: String = "customerGoods"
let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
// Get the stock to be shown
let item: StockCustomer = feedItems[indexPath.row] as! StockCustomer
// Configure our cell title made up of name and price
let titleStr = [item.number].compactMap { $0 }.joined(separator: " - ")
return myCell
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
let cellIdentifier: String = "customerGoods"
let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
myCell.textLabel?.textAlignment = .left
}
}
FeedCustomer.swift:
import Foundation
protocol FeedCustomerProtocol: class {
func itemsDownloaded(items: NSArray)
}
class FeedCustomer: NSObject, URLSessionDataDelegate {
weak var delegate: FeedCustomerProtocol!
let urlPath = "https://www.example.com/example/test.php"
func downloadItems() {
let url: URL = URL(string: urlPath)!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Error")
}else {
print("stocks downloaded")
self.parseJSON(data!)
}
}
task.resume()
}
func parseJSON(_ data:Data) {
var jsonResult = NSArray()
do{
jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
} catch let error as NSError {
print(error)
}
var jsonElement = NSDictionary()
let stocks = NSMutableArray()
for i in 0 ..< jsonResult.count
{
jsonElement = jsonResult[i] as! NSDictionary
let stock = StockCustomer()
//the following insures none of the JsonElement values are nil through optional binding
if let number = jsonElement[“number”] as? String,
let customer = jsonElement["customer"] as? String,
{
stock.customer = customer
stock.number = number
}
stocks.add(stock)
}
DispatchQueue.main.async(execute: { () -> Void in
self.delegate.itemsDownloaded(items: stocks)
})
}
}
StockCustomer.swift:
import UIKit
class StockCustomer: NSObject {
//properties of a stock
var customer: String?
var number: String?
//empty constructor
override init()
{
}
//construct with #name and #price parameters
init(customer: String) {
self.customer = customer
}
override var description: String {
return "Number: \(String(describing: number)), customer: \(String(describing: customer))"
}
}
You can achieve this by making an array of array. So something like this
[[{"customer": "customer1", "number": "123"}, {"customer": "customer1", "number": "456"}], [{"customer": "customer2", "number": "678"}, {"customer": "customer2", "number": "890"}]]
This is not the only data structure you can use to group. Another possibility is:
{"customer1": [{"customer": "customer1", "number": "123"}, {"customer": "customer1", "number": "456"}], "customer2": [{"customer": "customer2", "number": "678"}, {"customer": "customer2", "number": "890"}]}
Then you can use UITableView sections to group by customers. Section count would be the number of inside arrays and each section would contain as many rows as there are numbers in that inside array.
You can group a sequence based on a particular key using one of the Dictionary initializer,
init(grouping:by:)
The above method init will group the given sequence based on the key you'll provide in its closure.
Also, for parsing such kind of JSON, you can easily use Codable instead of manually doing all the work.
So, for that first make StockCustomer conform to Codable protocol.
class StockCustomer: Codable {
var customer: String?
var number: String?
}
Next you can parse the array like:
func parseJSON(data: Data) {
do {
let items = try JSONDecoder().decode([StockCustomer].self, from: data)
//Grouping the data based on customer
let groupedDict = Dictionary(grouping: items) { $0.customer } //groupedDict is of type - [String? : [StockCustomer]]
self.feedItems = Array(groupedDict.values)
} catch {
print(error.localizedDescription)
}
}
Read about init(grouping:by:) in detail here: https://developer.apple.com/documentation/swift/dictionary/3127163-init
Make the feedItems object in CustomerViewController of type [[StockCustomer]]
Now, you can implement UITableViewDataSource methods as:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.feedItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customerGoods", for: indexPath) as! CheckableTableViewCell
let items = self.feedItems[indexPath.row]
cell.textLabel?.text = items.compactMap({$0.number}).joined(separator: " - ")
//Configure the cell as per your requirement
return cell
}
Try implementing the approach with all the bits and pieces and let me know in case you face any issues.
My scenario I am using multiple array's for multiple cell label's. Per cell two different label's I am maintaining. I assigned separate array's for cell labels.
Like:
cell.accessibilityValue = String(id[indexPath.row])
cell.name_Label.text = name[indexPath.row]
cell.city_Label.text = city[indexPath.row]
here, all array values I am getting from my JSON and appending separately. Only name and city I am going to show but cell.accessibilityValue "ID" I am trying to store that ID within cell.accessibilityValue because I am maintaining two buttons within cell ADD and Plus. First Add will show, once user clicked that add button, It will call JSON and get ID values after that only ID values appending within cell.accessibilityValue = String(id[indexPath.row]) then reloading also I will.
Issues I am facing:
Initially no values in
cell.accessibilityValue = String(id[indexPath.row]) so I am
getting out of range error.
After add button I am trying to append the ID values into id array
and it should assign into my cell because after add clicked it will
hide and plus button will be display, for plus button click to get
that stored ID.
NOTE: here ID may have chance to come null, so if values available need to assign otherwise null.
Here my code
protocol CustomCellDelegate {
func cellButtonTapped(cell: CustomOneCell)
}
class CustomOneCell: UITableViewCell {
// Link those IBOutlets with the UILabels in your .XIB file
#IBOutlet weak var name_Label: UILabel!
#IBOutlet weak var city_Label: UILabel!
#IBOutlet weak var add_Button: UIButton!
var delegate: CustomCellDelegate?
#IBAction func add_buttonTapped(_ sender: Any) {
delegate?.cellButtonTapped(cell: self)
}
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CustomCellDelegate {
var id = [Int]() // This is from JSON but Initially no values
var name = [String]() // This is from JSON ["Item 1", "Item2", "Item3", "Item4"]
var city = [String]() // This is from JSON ["Item 1", "Item2", "Item3", "Item4"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK - UITableview
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return name.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomOneCell
cell.delegate = self
cell.accessibilityValue = String(id[indexPath.row]) // #1. Initially no values, So I am getting out of range Error
cell.name_Label.text = name[indexPath.row]
cell.city_Label.text = city[indexPath.row]
return cell
}
func cellButtonTapped(cell: CustomOneCell) {
let url = URL(string: "")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print("request failed \(error)")
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] {
for item in json {
let id = item["id"]!
self.id.append(id as! Int) // #2. After table load I am appending some values into id array
}
//Table reload to assign id values
}
} catch let parseError {
print("parsing error: \(parseError)")
let responseString = String(data: data, encoding: .utf8)
print("raw response: \(responseString!)")
}
}
task.resume()
}
The simplest way forward is to add a range check in tableView:cellForRowAt
if indexPath.row < id.count {
cell.accessibilityValue = String(id[indexPath.row])
}
But if it is possible I would look into creating a struct with all three values and maintaining one instead of three arrays
struct SomeData {
var id: Int
var name: String
var city: String
}
I'm confused with parsing the data from JSON. Actually, i extracted the whole data. But i am confused that how to apply it to table View rows. so, How to extract JSON Data and Apply it to dynamic tableView rows? lot of thanks in advance.
The JSON Data from URL is given below,
{
"main_result": "1",
"event_listing": [
{
"event_details": "Omega Events",
"pdf_url": "http://portal.shineevents.co.in/portal/assets/uploads/pdf/",
"modified_date": "2016-06-22 14:17:02"
},
{
"event_details": "Cobra Events",
"pdf_url": "http://portal.shineevents.co.in/portal/assets/uploads/pdf/",
"modified_date": "2016-06-22 14:17:18"
},
{
"event_details": "Kovai Events",
"pdf_url": "http://portal.shineevents.co.in/portal/assets/uploads/pdf/",
"modified_date": "2016-06-22 14:23:45"
}
]
}
Code I have try
import UIKit
class ViewController: UIViewController, UITableViewDataSource,UITableViewDelegate{
var labels = ["Taylor Swift","Eminem","Avlirl","Michael"] /* i use dummy array now*/
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
retrieveDataFromJASON()
}
func retrieveDataFromJASON()
{
let URL = NSURL(string: "http://portal.shineevents.co.in/portal/api_load/app_load_call")
let requestURL = NSMutableURLRequest(URL: URL!)
requestURL.HTTPMethod = "POST"
let postString = "api=event_list"
requestURL.addValue("123456", forHTTPHeaderField: "X-API-KEY")
requestURL.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(requestURL) { data, response, error in
guard error == nil && data != nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString2 = try! NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
print(responseString2) /*prints whole JSON Data*/
let events = responseString2["event_listing"] as? [[String: AnyObject]]
for eventName in events!
{
print(eventName["event_details"])
/* Prints:
Optional(Omega Events)
Optional(Cobra Events)
Optional(Kovai Events) // How to print only First event only
*/
}
}
task.resume()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return labels.count // How to use event_details.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableCell
cell.titles.text = labels[indexPath.row] // how to use event_details[indexPath.row]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
You need to declare instance variable of type [[String: AnyObject]] and use that with UITableViewDelegate method like below
var events : [[String: AnyObject]] = [[String: AnyObject]]()
Now initialize this events object when you get response and after that reload tableView.
self.events = responseString2["event_listing"] as? [[String: AnyObject]]
self.tableView.reloadData()
Now use this events object with UITableView methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return events.count // How to use event_details.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableCell
cell.titles.text = events[indexPath.row]["event_details"] as? String
return cell
}
You can get JSON data with converting it into NSData. Check my answer please : How to save JSON data from a POST Request into dictionary with Swifty Json?
Once you have dictionary you can easly parse it. See this: http://tech.ustwo.com/2014/08/01/ios-swift-dictionaries/
Also you should create your own cell on tableview so you can add your attributes to cells. Follow this tutorial :https://www.raywenderlich.com/129059/self-sizing-table-view-cells
Hope it helps.