can't use returend result Json in any class - json

i'm new to swift 2 langue and I'm try to use Json file inside my project so i go to use SwiftyJson library framework,but i got small problem that is i can't use the returned result from the son file in class of my project
this is my code
import UIKit
class NewsViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate{
#IBOutlet weak var championlist: UICollectionView!
#IBOutlet weak var menuButton: UIBarButtonItem!
private var imagesArray = ["About" , "About" , "About" , "About" , "Logo" , "Search" , "About"]
override func viewDidLoad() {
super.viewDidLoad()
if let path = NSBundle.mainBundle().pathForResource("data", ofType: "json") {
if let data = NSData(contentsOfFile: path) {
let json = JSON(data: data, options: NSJSONReadingOptions.AllowFragments, error: nil)
print (json["keys"]["117"])
let champlist = json["keys"].count
}
}
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
// Do any additional setup after loading the view.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UICollectionViewDataSource
func numberOfSectionsInCollectionView(championlist: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func collectionView(championlist: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.champlist.count
}
func collectionView(championlist: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = championlist.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionViewCell
cell.image.image = UIImage(named: imagesArray[indexPath.row])
cell.label.text = "\(indexPath.row)"
//var cell = collectionView.cellForItemAtIndexPath(indexPath)
cell.layer.borderWidth = 2.0
cell.layer.borderColor = UIColor.whiteColor().CGColor
// Configure the cell
return cell
}
}
i got error (Use of unresolved identifier 'chmplist'

You cannot have a variable defined inside a scope (set of braces) and then return it outside of it.
do this
var chmplist = 0
if let path = NSBundle.mainBundle().pathForResource("data", ofType: "json") {
if let data = NSData(contentsOfFile: path) {
let json = JSON(data: data, options: NSJSONReadingOptions.AllowFragments, error: nil)
print (json["keys"]["117"]) // this print Moha
chmplist = (json["keys"].count) // this print number of keys
}
}
return chmplist
UPDATE: after seeing the updated code:
championlist is not the same as champlist :).

Related

How to parse Json from URL and display in Collection View in Xcode

Here is a sample of my Api code that I am trying to parse
{"#iot.nextLink" : "Google.com","value" : [ {
"phenomenonTime" : "2020-02-12T01:38:17.622Z",
"resultTime" : "2020-02-12T01:38:17.622Z",
"result" : 1009.3,
"Datastream#1" : "Yahoo.com",
"FeatureOfInterest#2" : "bing.com",
"#iot.id" : 4093015,
"#iot.selfLink" : "youtube.com"},
{"phenomenonTime" : "2020-02-12T01:23:11.397Z",
"resultTime" : "2020-02-12T01:23:11.397Z",
"result" : 1009.7,
"Datastream#1" : "walmart.com",
"FeatureOfInterest#2" : "bestbuy.com",
"#iot.id" : 4092867,
"#iot.selfLink" : "gmail.com"}, ...]}
I have created structures to parse the Json
struct Initial: Decodable {
let value : [Blue]}
struct Blue: Decodable {
let phenomenonTime : String
let result : Double}
I only want to display the PhenomenonTime value and the result value. Next, I did
var url1 = ""
override func viewDidLoad() {
let url = URL(string: url1)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
guard let data = data else { return }
do {
let initial = try? JSONDecoder().decode(Initial.self, from: data)
print(initial?.value)
}catch {
print("Error")
}
}.resume()
}
Here is my code of me parsing the JSON. I can print the values
Optional([GTSeaLevelAPP.Blue(phenomenonTime: "2020-02-12T01:38:17.622Z", result: 1009.3),
GTSeaLevelAPP.Blue(phenomenonTime: "2020-02-12T01:23:11.397Z", result: 1009.7),...])
But, it doesn't allow me when I try to do
print(initial?.value.result)
An error comes up saying "Value of type '[Blue]' has no member 'result'". So, I don't know how to fix this issue of how to print just values or just phenomenonTime so I can put just put values in the collection view or just put phenomenonTime in another collection view. Also, I didn't know how to parse the Json so the collection view can see the array of just phenomenonTime.
extension ViewController:UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = pressureView.dequeueReusableCell(withReuseIdentifier: "check", for: indexPath) as? PressureCollectionViewCell
cell?.number.text=String(indexPath.row)
return cell!
}
Currently, I made it so it will just present a different number in each cell but I don't know how to get all the values into one array and all the phenomenonTime into one array and present them into the collectionview. When I try to refer to make the cell text display the values
cell?.number.text=initial?.value[indexPath.row]
It says:
"Use of unresolved identifier 'initial'"
So, what to do to fix it?
So, set your viewcontroller like:
class ViewController: UIViewController {
private lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.delegate = self
cv.dataSource = self
cv.backgroundColor = .lightGray
cv.translatesAutoresizingMaskIntoConstraints = false
return cv
}()
var url1 = "your_url"
private var cellId: String = "12312"
private var phenomenonTimeArray: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.collectionView)
NSLayoutConstraint.activate([
self.collectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
self.collectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
self.collectionView.topAnchor.constraint(equalTo: self.view.topAnchor),
self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
])
self.collectionView.register(PressureCollectionViewCell.self, forCellWithReuseIdentifier: self.cellId)
self.getDataFromServer()
}
func getDataFromServer() {
let url = URL(string: url1)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
guard let data = data else { return }
do {
let initial = try? JSONDecoder().decode(Initial.self, from: data)
if let value = initial?.value {
self.phenomenonTimeArray = value.map { (blue) -> String in
return blue.phenomenonTime
}
self.collectionView.reloadData()
}
} catch {
print("Error")
}
}.resume()
}
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.phenomenonTimeArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath) as! PressureCollectionViewCell
cell.item = phenomenonTimeArray[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return .init(width: collectionView.frame.width, height: 30)
}
}
And your cell(design your cell as per requirement):
class PressureCollectionViewCell: UICollectionViewCell {
var item: String? {
didSet {
self.label.text = item
}
}
private lazy var label: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.setupViews()
}
required init?(coder: NSCoder) {
fatalError()
}
private func setupViews() {
self.addSubview(self.label)
NSLayoutConstraint.activate([
self.label.leadingAnchor.constraint(equalTo: self.leadingAnchor),
self.label.trailingAnchor.constraint(equalTo: self.trailingAnchor),
self.label.topAnchor.constraint(equalTo: self.topAnchor),
self.label.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
}
}

My object array is nil while my data are correct

I try to display my data in a tableView using no framework to parse my data, but when I add my data to my table and debug it, it is nil at the output while my data I retrieve are well parses, have I forgotten something to do?
I use a structure for my parameters as this :
enum Types {
case School
case Hospital
case Station_Essence
case Restaurant
}
struct Adresse {
public var title: String
public var details: String?
public var type: Types
public var coordinate: [String: Any]
}
and in my ViewController, i proced as this :
class ListMapViewController: UIViewController {
#IBOutlet var TitleTableView: UITableView!
#IBOutlet var MapView: MKMapView!
var adresse: [Adresse]?
override func viewDidLoad() {
super.viewDidLoad()
self.TitleTableView.register(UINib(nibName: "ListMapTableViewCell", bundle: nil), forCellReuseIdentifier: "Adresse")
self.TitleTableView.delegate = self
self.TitleTableView.dataSource = self
guard let POI = URL(string: "https://moc4a-poi.herokuapp.com/") else {
return
}
let task = URLSession.shared.dataTask(with: POI) { (data, response, error) in
guard let dataResponse = data else { return }
if let json = try! JSONSerialization.jsonObject(with: dataResponse, options:[]) as? [[String: Any]] {
for data in json {
let title = data["title"] as! String
let details = data["details"] as? String
guard let type = data["type"] as? Int else { return }
let valueType = self.valueType(dataType: type)
guard let coordinates = data["coordinates"] as? [String: Any] else { return }
self.adresse?.append(Adresse(title: title, details: details, type: valueType, coordinate: coordinates))
}
}
print(self.adresse)
}
self.TitleTableView.reloadData()
task.resume()
}
private func valueType(dataType: Int) -> Types {
if(dataType == 1) {
return Types.School
} else if (dataType == 2) {
return Types.Hospital
} else if (dataType == 3) {
return Types.Station_Essence
} else {
return Types.Restaurant
}
}
}
extension ListMapViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.adresse?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Adresse", for: indexPath) as! ListMapTableViewCell
if let adresse = self.adresse?[indexPath.row] {
cell.draw(adresse: adresse)
}
return cell
}
}
extension ListMapViewController: UITableViewDelegate {
}
You have two big problems.
self.adresse is nil. You never assign it a value. So all of the self.adresse?... do nothing.
You call reloadData too soon. It needs to be done inside the completion block, after you update the data. And it needs to be on the main queue.
To fix #1, change var adresse: [Adresse]? to var adresse = [Adresse](). Then you can get rid of all the ? after uses of adresse.
To fix #2, add:
DispatchQueue.main.async {
self.TitleTableView.reloadData()
}
just after the print at the end of the completion block. Don't forget to remove the current call to reloadData.

How to work with Core Data saving JSON response,Show data when internet is offline in Swift 3?

I have already parsed JSON and showing in tableView which is working fine. Now my question is how will i save data offline and show when internet is not available offline using Core Data. I am working in Swift 3. If anyone can help me with screenshot it will be great help.
Below is my Code for fetching json and showing on tableView :
import UIKit
import SystemConfiguration
struct CellData {
var name:String
var address:String
public init(name:String,address:String){
self.name = name
self.address = address
}
}
///ViewController
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var tableViewData: UITableView!
var arrayData = [CellData]()
override func viewDidLoad() {
super.viewDidLoad()
if Reachability.isConnectedToNetwork(){
print("Internet Connection Available!")
fetchServerData()
}else{
let alert = UIAlertController(title: "No Internet connection", message: "Please ensure you are connected to the Internet", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
print("Internet Connection not Available!")
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! MyCellData
cell.lblTop.text = "😀\(arrayData[indexPath.row].name)"
cell.lblBottom.text = arrayData[indexPath.row].address
return cell
}
func fetchServerData(){
let prs = [
"author_id": "1780",
"get_deals_author": "1" as String
]
Service.StartWithoutLoading(prs as [String : AnyObject]?, onCompletion: { result in
let json = result as? NSDictionary
if let data = json as? [String:Any]{
if let err = data["status"] as? String, err == "success"{
if let data = data["result"] as? [Any]{
var arrayData = [CellData]()
for sectionObj in data{
if let sectionObjVal = sectionObj as? [String:Any]{
if let name_deal = sectionObjVal["name"] as? String{
if let address_deal = sectionObjVal["address"] as? String{
let dataValue = CellData.init(name: name_deal, address: address_deal)
arrayData.append(dataValue)
}
}
}
}
DispatchQueue.main.async { () -> Void in
self.arrayData.removeAll()
self.arrayData = arrayData
self.tableViewData.reloadData()
}
}
}
}
})
}
}
For Core Data, you need to create the entities you need in CoreData model .xcdatamodeld. Click on Add Entity and name your entity. Then add attributes which you require to save.
You can see this link on how to create the entities and attributes. After creating everything, we can write a CoreDataStack and a manager class or we can directly use the code pre-written in AppDelegate when we check on Core Data when creating a project. I'll here use the CoreDataStack class.
Here is the class
import Foundation
import CoreData
class CoreDataStack: NSObject {
static let moduleName = "YourProject"
static let shared = CoreDataStack()
private override init() {
super.init()
_ = self.persistentContainer
}
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: CoreDataStack.moduleName)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
print("Coordinator URL - \(storeDescription)")
})
return container
}()
}
Now we can make a manager class to insert the data. Let's say your entity is Person and its attributes are name and address
Here is the CoreDataManager class to insert, update, fetch data.
import UIKit
import CoreData
class CoreDataManager: NSObject {
class func addRecord(object:[String:Any]) {
let person = NSEntityDescription.insertNewObject(forEntityName: "Person", into: CoreDataStack.shared.persistentContainer.viewContext) as! Person
person.name = object["name"] as? String
person.address = object["address"] as? String
CoreDataStack.shared.saveContext()
}
class func getRecords() -> [Person]? {
let request:NSFetchRequest<Person> = Person.fetchRequest()
do {
let results = try CoreDataStack.shared.persistentContainer.viewContext.fetch(request)
return results
} catch {
print(error.localizedDescription)
}
return nil
}
}
You can call addRecord method in your ViewController class and it will save your data. I recommend that you pass the complete array and then add in core data and finally call saveContext().
Finally you can use getRecords to get all records.

nil while parsing JSON in Swift

I am doing some easy projects to learn new things. I started parsing JSON with SwiftyJSON. I am trying to show some JSON data to the tableView but now I am stuck. I do not know where is the nil and why. Can you help me guys? In given code I am trying to get the "Brands" and show them inside tableView or at least print those into console.
This is the .json file I have:
{
"Snuses": {
"Brands":{
"CATCH": [
{"Products":"white", "nicotine":"8.0"},
{"Products":"yellow", "nicotine":"8.0"}
],
"GENERAL": [
{"Products":"brown", "nicotine":"8.0"},
{"Products":"white", "nicotine":"8.0"}
]
}
}
}
And here I try to get the info like this:
var numberOfRows = 0
var snusBrandsArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
parseJSON()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func parseJSON(){
let path: String = NSBundle.mainBundle().pathForResource("snuses", ofType: "json") as String!
let jsonData = NSData(contentsOfFile: path) as NSData!
let readableJSON = JSON(data: jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil)
var brands = readableJSON["Snuses", "Brands"]
NSLog("\(brands)")
numberOfRows = readableJSON["Snuses"].count
for i in 1...numberOfRows{
var brands = "Snuses"
brands += "\(i)"
var name = readableJSON["Snuses", "Brands"].string as String!
snusBrandsArray.append(name)
}
}
What about something simple, like this? Below is Playground code but the parsing is the same.
//: Playground
import UIKit
import Foundation
var jsonStr = "{ \"Snuses\": { \"Brands\":{ \"CATCH\": [ {\"Products\":\"white\", \"nicotine\":\"8.0\"}, {\"Products\":\"yellow\", \"nicotine\":\"8.0\"} ], \"GENERAL\": [ {\"Products\":\"brown\", \"nicotine\":\"8.0\"}, {\"Products\":\"white\", \"nicotine\":\"8.0\"} ] } } }"
func parseJSON(jsonStr:String) throws -> [AnyObject]? {
var brandNameKeys:[AnyObject]?
let jsonData = jsonStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let json = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions())
if let brandNameDict = json["Snuses"]!?["Brands"] as? NSDictionary
{
brandNameKeys = brandNameDict.allKeys
}
return brandNameKeys
}
if let result = try parseJSON(jsonStr)
{
print(result)
}
In my Playground this outputs ["CATCH", "GENERAL"] which I think is what you want.
Here's a full UITableViewController demonstrating the solution in use:
import UIKit
class TableViewController: UITableViewController {
var data:[AnyObject]?
override func viewDidLoad() {
super.viewDidLoad()
if let path: String = NSBundle.mainBundle().pathForResource("Data", ofType: "json")
{
do
{
let jsonStr = try String(contentsOfFile: path)
data = try parseJSONStr(jsonStr)
}
catch _ {
print("Loading json failed")
}
}
}
// JSON Parsing
func parseJSONStr(jsonStr:String) throws -> [AnyObject]? {
var brandNameKeys:[AnyObject]?
let jsonData = jsonStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let json = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions())
if let brandNameDict = json["Snuses"]!?["Brands"] as? NSDictionary
{
brandNameKeys = brandNameDict.allKeys
}
return brandNameKeys
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let data = data
{
return data.count
}
else
{
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SampleCell", forIndexPath: indexPath)
if let rowData = data![indexPath.row] as? String
{
cell.textLabel?.text = rowData
}
return cell
}
}

populating Tableview with a function that uses SwiftyJSON

I have a function that returns parsed information out of a JSON string.
var info = [AppModel]()
func getEarthquakeInfo(completion: (results : NSArray?) ->Void ){
DataManager.getEarthquakeDataFromFileWithSuccess {
(data) -> Void in
let json = JSON(data: data)
if let JsonArray = json.array {
for appDict in JsonArray {
var ids: String? = appDict["id"].stringValue
var title: String? = appDict["title"].stringValue
var time: String? = appDict["time"].stringValue
var information = AppModel(idEarth: ids, title: title, time: time)
self.info.append(information)
completion(results: self.info)
}
}
}
}
This function uses SwiftyJSON and calls the web service using my DataManager class. When I print it out outside the function I get all the information I need. Now I want to use the title information to populate my TableView. Inside my cellForRowAtIndexPath I've tried filtering out my Earthinformation so that I could get just the title and put that into an array, and populate my tableView with that array. So far I've been unsuccessful, and I've been looking everywhere on how to do this and nothing I've tried or found worked. Can someone point me in the right direction on how to do this?
What I've done so far:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
getEarthquakeInfo( { (info) -> Void in
var Earthinformation = self.info as NSArray
let titleArray = Earthinformation["TITLE"] as NSArray // error: type int does not conform to protocol "StringLiteralConvertible"
cell.textLabel!.text = titleArray[indexPath.row]
})
return cell
}
3 records I get when I print out Earthinformation I get: ID: 146323, TITLE: M 1.6 - 27km E of Coso Junction, California, TIME: 2015-04-15 14:08:20 UTC,
, ID: 146346, TITLE: M 1.8 - 26km E of Coso Junction, California, TIME: 2015-04-15 14:08:20 UTC,
, ID: 146324, TITLE: M 2.4 - 26km NW of Anchor Point, Alaska, TIME: 2015-04-15 13:33:36 UTC,
Edit:
Sorry I should have included this before:
My AppModel.swift:
class AppModel: NSObject, Printable {
let idEarth: String
let title: String
let time: String
override var description: String {
return "ID: \(idEarth), TITLE: \(title), TIME: \(time), \n"
}
init(idEarth: String?, title: String?, time: String?) {
self.idEarth = idEarth ?? ""
self.title = title ?? ""
self.time = time ?? ""
}
}
And my DataManager.swift file:
let earthquakeURL = "http://www.kuakes.com/json/"
class DataManager {
class func getEarthquakeDataFromFileWithSuccess(success: ((websiteData: NSData) -> Void)) {
//1
loadDataFromURL(NSURL(string: earthquakeURL)!, completion:{(data, error) -> Void in
//2
if let urlData = data {
//3
success(websiteData: urlData)
}
})
}
class func loadDataFromURL(url: NSURL, completion:(data: NSData?, error: NSError?) -> Void) {
var session = NSURLSession.sharedSession()
// Use NSURLSession to get data from an NSURL
let loadDataTask = session.dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if let responseError = error {
completion(data: nil, error: responseError)
} else if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
var statusError = NSError(domain:"com.kuakes", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
completion(data: nil, error: statusError)
} else {
completion(data: data, error: nil)
}
}
})
loadDataTask.resume()
}
}
You are calling your getEarthquakeInfo function every time a cell is to be created. This is very unnecessary and may cause unintentional behavior (seeing as the getEarthquakeInfo function is asynchronous). I recommend utilizing the fact that you have a model array info already to use to populate your tableview. In viewDidLoad call your asynchronous function to retrieve the data for the model array. Example:
override func viewDidLoad() {
super.viewDidLoad()
getEarthquakeInfo { (info) in
// Your model array is now populated so we should reload our data
self.tableView.reloadData()
}
}
Now, adjust your UITableViewDataSource functions to properly handle the model array. Note that I am assuming that your info array is a property of the UITableViewController that is populating the tableView. Example:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier",
forIndexPath: indexPath) as UITableViewCell
// Note that I have no idea how you access the title of your AppModel
// object so you may have to adjust the below code
cell.textLabel!.text = self.info[indexPath.row].title
return cell
}
override func numberOfSectionsInTableView() {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) {
return info.count
}