Table View not updating with data fetched by HTTP Request - ios

I'm trying to populate a table view with data fetched from a http request (JSON) but it's not working. If I populate the Table View with static data everything works fine.. code snippet:
import UIKit
import Alamofire
//import SwiftyJSON
class ViewControllerNews : UITableViewController{
#IBOutlet var table: UITableView!
var posts = [FacebookPost]()
override func viewDidLoad() {
pullFacebookNews()
//loadSampleNews()
super.viewDidLoad()
}
func pullFacebookNews() -> Void {
let params = ["limit":"100", "access_token": myaccesstoken]
Alamofire.request( "https://graph.facebook.com/<page-id>/posts", parameters: params).responseJSON{ response in
if let responsejson = response.result.value {
let JSON = responsejson as! NSDictionary
let itemsArray: NSArray? = JSON.object(forKey: "data") as? NSArray
if(itemsArray != nil) {
for item in itemsArray! {
let thisitem = item as! NSDictionary
print(thisitem.object(forKey: "message") as? String)
print(thisitem.object(forKey:"created_time") as? String)
let title1 = thisitem.object(forKey: "message") as? String
let value1=thisitem.object(forKey:"created_time") as? String
if(title1 != nil && value1 != nil) {
let news = FacebookPost(title: title1!, value: value1!)
self.posts.append(news)
}
}}
}
}
do_table_refresh()
}
func do_table_refresh() {
DispatchQueue.global(qos: .background).async {
DispatchQueue.main.async {
self.table.reloadData()
}
}
}
func loadSampleNews() {
let news1 = FacebookPost(title: "ich bin ein datum", value: "Ich bin eine news")
let news2 = FacebookPost(title: "ich bin ein datum2", value: "Ich bin eine news2")
let news3 = FacebookPost(title: "ich bin ein datum3", value: "Ich bin eine news3")
posts += [news1, news2, news3]
}
override func numberOfSections(in: UITableView) -> Int {
return 1
}
override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
override func tableView(_: UITableView, cellForRowAt: IndexPath) -> UITableViewCell {
let cellIdentifier = "NewsTableViewCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: cellForRowAt as IndexPath) as! NewsTableViewCell
let news = posts[cellForRowAt.row]
cell.date.text = news.title
cell.news_text.text = news.value
return cell
}
}
The loadSampeNews() works perfectly, but pullFacebookNews() does not populate the table. While debugging the array is filled..

If you set breakpoints, you will see that do_table_refresh() gets called before you hit if let responsejson = response.result.value. This is because the Alamofire call has a completion handler. You have to wait until the internet call is complete before you call do_table_refresh().
So you essentially just have to move do_table_refresh() if all of your data is loading correctly like you say it is.
func pullFacebookNews() -> Void {
let params = ["limit":"100", "access_token": myaccesstoken]
Alamofire.request( "https://graph.facebook.com/<page-id>/posts", parameters: params).responseJSON{ response in
if let responsejson = response.result.value {
let JSON = responsejson as! NSDictionary
let itemsArray: NSArray? = JSON.object(forKey: "data") as? NSArray
if(itemsArray != nil) {
for item in itemsArray! {
let thisitem = item as! NSDictionary
print(thisitem.object(forKey: "message") as? String)
print(thisitem.object(forKey:"created_time") as? String)
let title1 = thisitem.object(forKey: "message") as? String
let value1=thisitem.object(forKey:"created_time") as? String
if(title1 != nil && value1 != nil) {
let news = FacebookPost(title: title1!, value: value1!)
self.posts.append(news)
}
}
}
self.do_table_refresh()
}
}
}
Additionally, don't name your methods with that syntax. It is not best practice. Should be doTableRefresh() or something.

Related

Swift Firebase UITableViewCell loads before Data to populate cell is available

I am pushing data which is an array of strings to a tableview controller. These strings are "uid's" which are users in my database. With this array I make a call to firebase to extract all users and then do a match to the uid's. I am getting the correct data, yet I print out everything to make sure when the data is available and the data is available only after the tableview cell loads which causes the data to be nil causing a crash or just empty data. How can I make the data load first and then the cell so the data is available for display?
I've created functions for the data and now I have it in my viewDidLoad. Also, you'll see I have tried adding the firebase call into the Cell setup but of course that does not work.
Array of strings
var data = [String]()
viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
Database.database().reference().child("Businesses").observe(.value, with: { snapshot in
if snapshot.exists() {
self.businessUID = snapshot.value as? NSDictionary
if let dict = snapshot.value as? NSDictionary {
for item in dict {
let json = JSON(item.value)
let businessUid = json["uid"].stringValue
for uid in self.data {
if uid == businessUid {
let customerValue = self.businessUID?[uid]
self.businessDictionary = customerValue as! NSDictionary
print(self.businessDictionary)
print("Just printed the business dictionary")
}
}
}
}
} else {
print("does not exist")
}
})
}
Tableview Cell
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomerViewsSelectedBusinessesCell
print(self.businessDictionary)
print("Print the dictionary here to check the values")
let businessValues = self.businessDictionary
let uid = self.data.description
print(businessValues)
print("printed the business values")
if let dict = businessValues {
for item in dict {
let json = JSON(item.value)
let businessUid = json["uid"].stringValue
for uid in self.data {
if uid == businessUid {
let customerValue = self.businessUID?[uid]
self.businessData = customerValue as? NSDictionary
print(self.businessData)
print("Printing matching the uid values")
}
}
}
}
cell.businessName.text = businessData?["businessName"] as? String
cell.businessStreet.text = businessData?["businessStreet"] as? String
cell.businessCity.text = businessData?["businessCity"] as? String
cell.businessState.text = businessData?["businessState"] as? String
let businessProfilePicture = businessData?["profPicString"] as? String
if (businessProfilePicture!.characters.count) > 0 {
let url = URL(string: (businessProfilePicture!))
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
let image = UIImage(data: data!)?.potter_circle
cell.profileImage.contentMode = UIView.ContentMode.scaleAspectFill
cell.profileImage.image = image
}
}
} else {
let image = UIImage(named: "default")?.potter_circle
cell.profileImage.contentMode = UIView.ContentMode.scaleAspectFill
cell.profileImage.image = image
}
return cell
}
Here is my solution. Got it to work. Appened and used "usersArray" to get and display the data.
var data = [String]()
var usersArray = [NSDictionary?]()
override func viewDidLoad() {
super.viewDidLoad()
Database.database().reference().child("Businesses").observe(.value, with: { snapshot in
if snapshot.exists() {
self.businessUID = snapshot.value as? NSDictionary
if let dict = snapshot.value as? NSDictionary {
for item in dict {
let json = JSON(item.value)
let businessUid = json["uid"].stringValue
for uid in self.data {
if uid == businessUid {
let customerValue = self.businessUID?[uid]
self.usersArray.append(customerValue as! NSDictionary)
self.followUsersTableView.reloadData()
}
}
}
}
} else {
print("does not exist")
}
})
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.usersArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomerViewsSelectedBusinessesCell
let user : NSDictionary?
user = self.usersArray[indexPath.row]
cell.businessName.text = String(user?["businessName"] as! String)
cell.businessStreet.text = String(user?["businessStreet"] as! String)
cell.businessCity.text = String(user?["businessCity"] as! String)
cell.businessState.text = String(user?["businessState"] as! String)
let businessProfilePicture = String(user?["profPicString"] as! String)
if (businessProfilePicture.characters.count) > 0 {
let url = URL(string: (businessProfilePicture))
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
let image = UIImage(data: data!)?.potter_circle
cell.profileImage.contentMode = UIView.ContentMode.scaleAspectFill
cell.profileImage.image = image
}
}
} else {
let image = UIImage(named: "default")?.potter_circle
cell.profileImage.contentMode = UIView.ContentMode.scaleAspectFill
cell.profileImage.image = image
}
return cell
}

Swift 3 / Alamofire : I am not able to fetch the data on UITableView

I am using Alamofire and trying to fetch data on my tableview, however I am not able to get the data. When I use the cmd Print, its showing me the data but not able to fetch the data. How can I fetch the data on my tableview?
Please find the code below:-
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSURLConnectionDelegate {
//let myarray = ["item1", "item2", "item3"]
var tableData = Array<Group>()
var arrRes = [[String:AnyObject]]() //Array of dictionary
var group = [Group]()
#IBOutlet weak var tableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
loadGroups()
}
func loadGroups(){
let testhappyhour:Group = Group(tempName: "TEST", tempID: "TESST", icons: "TEST", tempgbcount: "TEST")
self.group.append(testhappyhour)
//let groupQuery:String = "http://jsonplaceholder.typicode.com/users"
Alamofire.request("http://jsonplaceholder.typicode.com/users").responseJSON
{ response in switch response.result {
case .success(let JSON):
let response = JSON as! NSArray
for item in response { // loop through data items
let obj = item as! NSDictionary
let happyhour = Group(tempName:obj["NAME"] as! String, tempID:obj["id"] as! String, icons:obj["icon"] as! String, tempgbcount:obj["TOTAL"] as! String)
self.group.append(happyhour)
}
self.tableview.reloadData()
case .failure(let error):
print("Request failed with error: \(error)")
}
}
}
func convertToArray(text: String) -> [Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableview.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return myarray.count
return arrRes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell", for: indexPath) as! UITableViewCell
// cell.textLabel?.text = myarray[indexPath.item]
let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "groupCell")!
var dict = arrRes[indexPath.row]
cell.textLabel?.text = dict["NAME"] as? String
cell.detailTextLabel?.text = dict["TOTAL"] as? String
return cell
}
}
Thank you!!
Need to change loadGroups function like this
func loadGroups(){
let testhappyhour:Group = Group(tempName: "TEST", tempID: "TESST", icons: "TEST", tempgbcount: "TEST")
self.group.append(testhappyhour)
Alamofire.request("http://jsonplaceholder.typicode.com/users").responseJSON
{ response in switch response.result {
case .success(let JSON):
let response = JSON as! NSArray
for item in response { // loop through data items
let obj = item as! NSDictionary
let happyhour = Group(tempName:obj["NAME"] as! String, tempID:obj["id"] as! String, icons:obj["icon"] as! String, tempgbcount:obj["TOTAL"] as! String)
self.group.append(happyhour)
self.arrRes.append(obj) // ADD THIS LINE
}
self.tableview.reloadData()
case .failure(let error):
print("Request failed with error: \(error)")
}
}
}
Array 'group' is appended with the Alamofire responses, but Array 'arrRes' is used as the table view data source. If you use self.group instead of arrRes in the data source methods, the table should update with the new groups received in the Alamofire response.

Swift Adding objects from on array to another array correctly?

So I have 2 NSMutableArrays, one called testArray and the other called jsonArray. jsonArray gets its objects from a mysql server using json and php. Then those same objects in jsonArray are inserted in testArray. I did print(jsonArray, testArray) and what showed in the logs were this.
I also have a NSObject class called Test, if that helps..
For the jsonArray
{
testName = GreenCorn;
testStatus1 = 12;
testStatus2 = 13;
testURL = "";
id = 1;
}
For the testArray
"<CustomCellSwift.Test: 0x17414df70>"
Now I'm new to iOS Swift but I don't know if I inserted the jsonArray into testArray correctly. Here is the code I used. Also, I'm using a custom tableview and its supposed to show testArray.count, its empty cells but its showing the several rows that I have in jsonArray.
var followedArray: NSMutableArray = []
var testArray: NSMutableArray = []
var jsonArray: NSMutableArray = []
var filteredArray: NSArray = []
var isFiltered: Bool = false
// Number of Rows in Section
internal func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if !isFiltered {
if section == 0 {
return followedArray.count
}
else if section == 1 {
return testArray.count
}
}
return filteredArray.count
}
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let CellIdentifier = "Cell"
var cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier) as! CustomCell
if cell != cell {
cell = CustomCell(style: UITableViewCellStyle.default, reuseIdentifier: CellIdentifier)
}
// Coloring TableView
myTableView.backgroundColor = UIColor.white
// Configuring the cell
var testObject: Test
print("before ifFiltered")
if !isFiltered {
if indexPath.section == 0 {
print("isFiltered if")
testObject = followedArray[indexPath.row] as! Test
cell.populateCell(testObject, isFollowed: true, indexPath: indexPath, parentView: self)
}
else if indexPath.section == 1 {
print("isFiltered if 2")
testObject = testArray[indexPath.row] as! Test
cell.populateCell(testObject, isFollowed: false, indexPath: indexPath, parentView: self)
}
}
else {
print("isFiltered else")
testObject = filteredArray[indexPath.row] as! Test
cell.populateCell(testObject, isFollowed: false, indexPath: indexPath, parentView: self)
}
return cell
}
// Retrieving Data from Server
func retrieveData() {
let getDataURL = "http://exampleip.org/json.php"
let url: NSURL = NSURL(string: getDataURL)!
do {
let data: Data = try Data(contentsOf: url as URL)
jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSMutableArray
// Setting up testArray
let testArray: NSMutableArray = []
// Looping through jsonArray
for i in 0..<jsonArray.count {
// Create Test Object
let tID: String = (jsonArray[i] as AnyObject).object(forKey: "id") as! String
let tName: String = (jsonArray[i] as AnyObject).object(forKey: "testName") as! String
let tStatus1: String = (jsonArray[i] as AnyObject).object(forKey: "testStatus1") as! String
let tStatus2: String = (jsonArray[i] as AnyObject).object(forKey: "testStatus2") as! String
let tURL: String = (jsonArray[i] as AnyObject).object(forKey: "testURL") as! String
// Add Test Objects to Test Array
testArray.add(Test(testName: tName, andTestStatus1: tStatus1, andTestStatus2: tStatus2, andTestURL: tURL, andTestID: tID))
print("retrieveData")
print(jsonArray, testArray)
}
}
catch {
print("Error: (Retrieving Data)")
}
myTableView.reloadData()
}
Am I doing this correctly? Why does my tableview have empty cells?
First, your networking/serialization code shouldn't be in your ViewController, but this is a better way to do things:
func retrieveData() {
let getDataURL = "http://exampleip.org/json.php"
let url: NSURL = NSURL(string: getDataURL)!
do {
let data: Data = try Data(contentsOf: url as URL)
guard let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String : AnyObject]] else {
print("Error Retrieving Data")
return
}
let testArray = jsonArray.flatMap(Test.init)
// make sure the add the result in your viewController
self.myTableView.models = testArray
}
catch {
print("Error: (Retrieving Data)")
}
myTableView.reloadData()
}
extension Test {
convenience init?(with jsonDictionary: [String : AnyObject]) {
guard let tID = jsonDictionary["id"] as? String, let tName = jsonDictionary["testName"] as? String, let tStatus1 = jsonDictionary["testStatus1"] as? String,
let tStatus2 = jsonDictionary["testStatus2"] as? String, let tURL = jsonDictionary["testURL"] as? String else {
return nil
}
self(testName: tName, andTestStatus1: tStatus1, andTestStatus2: tStatus2, andTestURL: tURL, andTestID: tID)
}
}
I couldn't really test it so there may be some errors, but that should point you in the right direction.
Removing this line of code worked.
let testArray: NSMutableArray = []

Swift PHP post request set global variable from task

I successfully retrieve data from database by using post request. (I don't want to use get request cuz I want to send a verification to php.) Don't worry about the php part, it should be fine.
import UIKit
class mainPage: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var toolBar: UIToolbar!
var values:NSArray = []
#IBOutlet weak var Open: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
Open.target = self.revealViewController()
Open.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
get()
}
func get(){
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.percyteng.com/orbit/getAllpostsTest.php")!)
request.HTTPMethod = "POST"
let postString = "user=\("ios")"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let array = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
self.values = array
}
task.resume()
dispatch_async(dispatch_get_main_queue()) { tableView.reloadData()}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if values.count > 20{
return 20
}
else{
return values.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as!postCell
let maindata = values[values.count-1-indexPath.row]
if maindata["category"] as? String == "Services"{
cell.postImg.image = UIImage(named: "tile_services")
}
else if maindata["category"] as? String == "exchange"{
cell.postImg.image = UIImage(named: "tile_exchange")
}
else if maindata["category"] as? String == "Tutors"{
cell.postImg.image = UIImage(named: "tile_tutoring")
}
else if maindata["category"] as? String == "Sports"{
cell.postImg.image = UIImage(named: "tile_sports")
}
else if maindata["category"] as? String == "Sublet"{
cell.postImg.image = UIImage(named: "tile_sublet")
}
else if maindata["category"] as? String == "Events"{
cell.postImg.image = UIImage(named: "tile_events")
}
else{
cell.postImg.image = UIImage(named: "tile_carpool")
}
if maindata["category"] as? String == "Services" || maindata["category"] as? String == "Tutors" || maindata["category"] as? String == "Events"{
cell.title.text = maindata["title"] as? String
}
else if maindata["category"] as? String == "Sublet" || maindata["category"] as? String == "Rideshare"{
cell.title.text = maindata["location"] as? String
}
else{
cell.title.text = maindata["item"] as? String
}
if maindata["category"] as? String == "Sublet" || maindata["category"] as? String == "Rideshare"{
cell.location.text = ""
}
else{
cell.location.text = maindata["location"] as? String
}
cell.category.text = maindata["category"] as? String
cell.price.text = maindata["price"] as? String
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
}
So I have a globale variable called values which is a NSArray, and I want to set the value of this array to be the array that I retrieve from database. However, in function get(), the post request acts as another thread and I have to write self.values = array which doesn't change the value of my global variable.
I need that value to organize my tableview in the main array.
Basically, my question is how can I get the value from a closure and set it to a global variable.
Thank you! Let me know if you guys don't understand what I'm saying.
You need a completion handler in your func get() as you're doing the dataTaskWithRequest which is an Async call. Try this:
func get(finished: (isDone: Bool) -> ()){
//your code
data, response, error in
if error != nil {
finished(isDone: false)
print("error=\(error)")
return
}
print("response = \(response)")
let array = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
self.values = array
}
}
task.resume()
finished(isDone: true)
}
And then in your viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
get { success in
if success{
//reload your tableview here
}
}
The closure implicitly retains self, so you are actually modifying that property. But you need to refresh your tableView after the data is retrieved within the closure, either using reloadCellsAtIndexPath, insertCellsAtIndexPath, or reloadData. The latter is the simplest approach, but completely replaces the current state of the table.
Additionally, you are causing a retain cycle in your closure. You should pass in self as a weak or unowned property to let ARC do its job. For more information on that: http://krakendev.io/blog/weak-and-unowned-references-in-swift
Example:
func get(){
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.percyteng.com/orbit/getAllpostsTest.php")!)
request.HTTPMethod = "POST"
let postString = "user=\("ios")"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let array = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
self.values = array
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
self.tableView?.reloadData();
}
}
task.resume()
}

parsing JSON it's not working in Swift

I'm creating a simple app that shows the details of every character fo Star Wars using SWAPI. Now i'm trying to get the species but Xcode is telling me that found a nil while unwrapping an optional value when is trying to print _species. Here's the code:
func DownlaodCompleted(complete: DownloadComplete) {
let url = NSURL(string: _urlperson)!
Alamofire.request(.GET, url).responseJSON { (response: Response<AnyObject, NSError>) -> Void in
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject> {
if let height = dict["height"] as? String {
self._height = height
}
if let gender = dict["gender"] as? String {
self._gender = gender
}
if let birthYear = dict["birth_year"] as? String {
self._birthYear = birthYear
}
if let species = dict["species"] as? [Dictionary<String, String>] {
let urlSpecies = NSURL(string: self._urlSpecies)!
Alamofire.request(.GET, urlSpecies).responseJSON(completionHandler: { (response2: Response<AnyObject, NSError>) -> Void in
let result = response2.result
if let speciesDict = result.value as? Dictionary<String, AnyObject> {
if let name = speciesDict["name"] as? String {
self._species = name
}
}
})
}
print(self._species)
print(self._height)
}
}
}
and here the class of Constants:
let URL_BASE = "http://swapi.co"
let URL_PEOPLE = "/api/people/"
let URL_SPECIES = "/api/species/1/"
typealias DownloadComplete = () -> ()
Here's sample code that I used after creating an empty "Single View Project", and adding the 2 "pods" Alamofire, and SwiftyJSON to the project.
The sample code has one of your URLs and a commented out URL to another site.
import UIKit
import Alamofire
import SwiftyJSON // No such module "SwiftyJSON"
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableView: UITableView!
var arrResults = [[String:AnyObject]]() //Array of dictionary
override func viewDidLoad() {
super.viewDidLoad()
self.view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
self.tableView = UITableView(frame:self.view!.frame)
self.tableView!.delegate = self
self.tableView!.dataSource = self
self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "jsonCell")
self.view?.addSubview(self.tableView)
Alamofire.request(.GET, "http://swapi.co/api/people/?format=json").responseJSON { (responseData) -> Void in
let swiftyJsonVar = JSON(responseData.result.value!)
for element in swiftyJsonVar["results"].arrayValue {
let name = element["name"].string!
let homeworld = element["homeworld"].string!
let object : Dictionary<String, String> = ["name": name, "homeworld": homeworld]
self.arrResults.append(object)
}
if self.arrResults.count > 0 {
self.tableView.reloadData()
}
}
// Alamofire.request(.GET, "http://api.androidhive.info/contacts/").responseJSON { (responseData) -> Void in
// let swiftyJsonVar = JSON(responseData.result.value!)
//
// if let resData = swiftyJsonVar["contacts"].arrayObject {
// self.arrResults = resData as! [[String:AnyObject]]
// }
// if self.arrResults.count > 0 {
// self.tableView.reloadData()
// }
// }
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "jsonCell")
var dict = arrResults[indexPath.row]
// Use these lines with: "http://swapi.co/api/people/?format=json"
cell.textLabel?.text = dict["name"] as? String
cell.detailTextLabel?.text = dict["homeworld"] as? String
// Use these lines with: "http://api.androidhive.info/contacts/"
// cell.textLabel?.text = dict["name"] as? String
// cell.detailTextLabel?.text = dict["email"] as? String
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrResults.count
}
}

Resources