Getting JSON data to populate a TableView from an Array - arrays

I'm able to successfully populate the array with my JSON data inside of the loop, and I'm trying to populate the cells of my TableView with the same information, but currently the list comes up with no content.
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var table: UITableView!
var headlines = [String]()
let baseURL = "http://api.nytimes.com/svc/topstories/v1/business.json?api-key=123456789"
override func viewDidLoad() {
getJSON()
super.viewDidLoad()
self.table.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.table.dataSource = self
self.table.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getJSON() {
let url = NSURL(string: baseURL)
let request = NSURLRequest(URL: url!)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request){ (data, response, error) -> Void in
if error == nil {
let SwiftyJSON = JSON(data: data!)
let theTitle = SwiftyJSON["results"].arrayValue
for title in theTitle{
let titles = title["title"].stringValue
self.headlines.insert(titles, atIndex: 0)
//print("- " + titles)
}
print(self.headlines)
}
else {
print("there was an error")
}
}
task.resume()
}
// From the UITAbleViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return headlines.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.table.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
cell.textLabel!.text = self.headlines[indexPath.row]
return cell
}
// From the UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You tapped on cell # \(indexPath.row)")
}
}

The task is asynchronous, so when you've loaded the array you have to reload your table
func getJSON() {
let url = NSURL(string: baseURL)
let request = NSURLRequest(URL: url!)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request){ (data, response, error) -> Void in
if error == nil {
let SwiftyJSON = JSON(data: data!)
let theTitle = SwiftyJSON["results"].arrayValue
for title in theTitle{
let titles = title["title"].stringValue
self.headlines.insert(titles, atIndex: 0)
//print("- " + titles)
}
print(self.headlines)
self.table.reloadData()
}
else {
print("there was an error")
}
}
task.resume()
}

Related

UICollectionView in UITableView - I want to show data in CollectionVewCell

I want to show data in UICollectionView. Which is coming from UITableView cell. My main concern is this. I am passing a key catgID from cellForRowAt in another API and getting data from it. But data is not coming proper way.
I am passing catgID from cellForRowAt and getting in another API which will show the list of data for UICollectionViewCells. Now data is coming but not in proper way.
This is my UITableView class for tableview index.
import UIKit
import Reachability
import Alamofire
var arrayMenuProducts = [structMenuProducts]()
struct structMenuProducts {
var id:Int
var product_name:String
var category:String
var product_image:String
var price:String
var unit_price:Double
var addons:NSArray
}
class MenuVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
var reachability = Reachability()!
#IBOutlet weak var tableview: UITableView!
var arrayMenuCat = [structMenuCat]()
struct structMenuCat{
var id:Int
var category_name:String
}
override func viewDidLoad() {
super.viewDidLoad()
menuVegAPI()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayMenuCat.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
catgID = arrayMenuCat[indexPath.row].id
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell1") as! MenuTableCell
cell.lblCategoryTitle.text = arrayMenuCat[indexPath.row].category_name
cell.collectionviewOne.reloadData()
// let catid = arrayMenuCat[indexPath.row].id
// print(catid)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 216
}
func menuVegAPI()
{
if (reachability.connection == .wifi) || (reachability.connection == .cellular)
{
arrayMenuCat.removeAll()
SwiftLoader.show(animated: true)
let url = BaseUrl + ViewController.sharedInstance.menuCategory
print(url)
Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default).responseJSON { response in
SwiftLoader.hide()
switch response.result {
case .success:
let json = response.result.value
print(json)
let code = (json as AnyObject).object(forKey: "code") as! Int
print(code)
if code == 200
{
let data = (json as AnyObject).object(forKey: "data") as? NSArray
for alldata in data!
{
let id = (alldata as AnyObject).object(forKey: "id") as! Int
let category_name = (alldata as AnyObject).object(forKey: "category_name") as! String
let arr = structMenuCat(id: id, category_name: category_name)
self.arrayMenuCat.append(arr)
// self.menuProductsAPI(categoryid: id)
}
self.tableview.reloadData()
}
else
{
}
case .failure:
print("error")
}
}
}
else
{
alert(title: "", message: "Please Check Your Internet Connection")
}
}
}
This is my TableViewCell type class. In this class I am show data on CollectionView. Its code is here
import UIKit
import Alamofire
import Reachability
var catgID : Int!
var collectionreload : UICollectionView?
class MenuTableCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
var reachability = Reachability()!
#IBOutlet weak var lblCategoryTitle: UILabel!
#IBOutlet weak var collectionviewOne: UICollectionView!
var arrayMenuProducts = [structMenuProducts]()
struct structMenuProducts {
var id:Int
var product_name:String
var category:String
var product_image:String
var price:String
var unit_price:Double
var addons:NSArray
}
override func awakeFromNib() {
super.awakeFromNib()
collectionreload = self.collectionviewOne
print(arrayMenuProducts)
print(catgID ?? 0)
menuProductsAPI(categoryid: catgID!)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrayMenuProducts.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellRID", for: indexPath) as! MenuCollectionViewCell
let abc = arrayMenuProducts[indexPath.row].product_name
print(abc)
// if catgID == Int(arrayMenuProducts[indexPath.row].category)
// {
cell.lblTitleForVeg.text = arrayMenuProducts[indexPath.row].product_name
cell.lblForPriceVeg.text = "$\(arrayMenuProducts[indexPath.row].unit_price)"
}
func menuProductsAPI(categoryid:Int)
{
if (reachability.connection == .wifi) || (reachability.connection == .cellular)
{
SwiftLoader.show(animated: true)
arrayMenuProducts.removeAll()
let url = BaseUrl + ViewController.sharedInstance.menuProducts + "categoryid=\(categoryid)"
print(url)
Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default).responseJSON { response in
switch response.result {
case .success:
let json = response.result.value
print(json)
// self.tableview.reloadData()
let code = (json as AnyObject).object(forKey: "code") as! Int
print(code)
if code == 200
{
let data = (json as AnyObject).object(forKey: "data") as? NSArray
DispatchQueue.main.async {
for alldata in data!
{
let id = (alldata as AnyObject).object(forKey: "id") as! Int
let product_name = (alldata as AnyObject).object(forKey: "product_name") as! String
let category = (alldata as AnyObject).object(forKey: "category") as! String
let product_image = (alldata as AnyObject).object(forKey: "product_image") as! String
let price = (alldata as AnyObject).object(forKey: "price") as! String
let unit_price = (alldata as AnyObject).object(forKey: "unit_price") as! Double
let addons = (alldata as AnyObject).object(forKey: "addons") as? NSArray
let arr = structMenuProducts(id: id, product_name: product_name, category: category, product_image: product_image, price: price, unit_price: unit_price, addons: addons!)
self.arrayMenuProducts.append(arr)
}
self.collectionviewOne.reloadData()
SwiftLoader.hide()
}
}
else
{
}
case .failure:
print("error")
}
}
}
else
{
// alert(title: "", message: "Please Check Your Internet Connection")
}
}
}
I want to show data coming in CollectionView in a proper formate. If Tableview index == 0 and Category id is coming 10 then. Category id 10 will first then one by one in a sequence I want to pass category id. In my case Category id is not coming in a queue.
Update the tableview datasource method as
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell1") as! MenuTableCell
cell.lblCategoryTitle.text = arrayMenuCat[indexPath.row].category_name
cell.menuProductsAPI(categoryid: arrayMenuCat[indexPath.row].id)
return cell
}
And remove menuProductsAPI(categoryid: catgID!) from awakeFromNib method

Swift: How can I get the records from the database according to the cell pressed

Is it possible to get the data from the external database when a UItableViewCell is pressed?
I managed to create a UItableView where I am displaying the data from the database. If I press a cell then all the data that are linked to it should be displayed. For eg. if I have 4 main categories in the database such as TOOLS, OTHERS, SECURITY, PETS and each of them has its sub-catecory and are linked with each other in the database. So if I click on Pets, it should filter out and only Show me CATS, DOGS, COWS, LIONS. When I run this SQL I am able to get the information but cant figure it this out on Swift.
UItableViewCell is in my FirstviewController and its the Main Category .
When I click here it goes to my destination VC and has the table again in here.enter image description here
DestViewController is the sub-category
enter image description here
My CategoryList_ViewController.swift
import Foundation
import UIKit
import WebKit
class CategoryList_ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
#IBAction func refresh(sender: AnyObject) {
get()
}
var values:NSArray = []
override func viewDidLoad() {
super.viewDidLoad()
get();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func get(){
let url = NSURL(string: "c:\deskstop\mobiletec\assignment\assignment2\cat.php")
let data = NSData(contentsOfURL: url!)
values = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
tableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return values.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CategoryList_TableViewCell
let maindata = values[indexPath.row]
cell.categoryLabel.text = maindata["NAME"] as? String
return cell;
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "catView" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let value = values[indexPath.row]
let controller = segue.destinationViewController as! SubCatergory_ViewController
controller.cate_Id = value["id"] as! String
controller.catTitleRec = value["NAME"] as! String
}
}
}
}
my SubCatergory_ViewController.swift
import Foundation
import UIKit
import WebKit
class SubCatergory_ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var caID: UILabel!
#IBOutlet weak var catTitle_Label: UILabel!
#IBAction func refresh(sender: AnyObject) {
get()
}
var values:NSArray = []
var catTitleRec = ""
var cate_Id = ""
override func viewDidLoad() {
super.viewDidLoad()
catTitle_Label.text = catTitleRec
caID.text = cate_Id
get();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func get(){
let request = NSMutableURLRequest(URL: NSURL(string: "c:\deskstop\mobiletec\assignment\assignment2\subcat.php")!)
request.HTTPMethod = "GET"
let postString = "a=\(cate_Id)"
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 responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return values.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! subCateListTableViewCell
let maindata = values[indexPath.row]
cell.categoryLabel.text = maindata["NAME"] as? String
return cell;
}
}
and my subcat.php
<?php
$connection = mysql_connect(........);
$catefilter = $_GET['a'];
if(!$connection){
die('Connection Failed');
}
else{
$dbconnect = #mysql_select_db($database_UNIASSIGNMENT, $connection);
if(!$dbconnect){
die('Could not connect to Database');
}
else{
$query = 'SELECT category_group.group_id , category.NAME FROM category_group LEFT JOIN category ON category.id = category_group.category_id WHERE category_group.group_id =' . $catefilter ;
$resultset = mysql_query($query, $connection);
$records= array();
while($r = mysql_fetch_assoc($resultset)){
$records[] = $r;
}
echo json_encode($records);
}
}
?>
My first VC works fine but my second VC doesnot get the data
Thanks for your time :)
SK
To access the cell that has been pressed, you need to call the didSelectRowAtIndexPath function.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let value = values[indexPath.row]
let vc = storyboard?.instantiateViewController(withIdentifier: "SubCatergory_ViewController") as! SubCatergory_ViewController
vc.cate_Id = value["NAME"] as! String
//self.navigationController?.pushViewController(vc, animated: true)
self.present(vc, animated: true, completion: nil)
}
First you get the value out of your values Array on the indexPark.row. Then you instantiate your second viewController.
Then you set your String value of cate_Id to the desired String value of your item value. And then you just need to present the new viewController.
If you're using a UINavigationController and you want a "back" button, then you use: self.navigationController?.pushViewController(vc, animated: true)
If you just want to present the viewController, you use self.present(vc, animated: true, completion: nil)
Comment or uncomment whatever presentation method you prefer.

Array list item count and number of element in an array mismatch while using swiftyjson?

import UIKit
import Alamofire
import SwiftyJSON
class RecentAdded: UIViewController ,UITableViewDataSource,UITableViewDelegate{
#IBOutlet var tableView: UITableView!
var list:JSON!
var sendurl:String!
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(.GET, "http://api.dirble.com/v2/stations/recent", parameters: ["token": "260674ecb51572a8faa4e77199"])
.responseJSON { response in
if let json = response.result.value {
self.list = JSON(data: response.data!)
print(self.list) /// Showing less element if element is more than 25
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.reloadData()
print(self.list.arrayValue.capacity) // Printing the actual capacity
}
}
// Do any additional setup after loading the view.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.list.arrayValue.capacity
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! RecentCellTableViewCell
let sampleArray = self.list.array
let imageURL:String! = sampleArray![indexPath.row]["image"]["thumb"]["url"].stringValue
if imageURL != ""{
Alamofire.request(.GET, imageURL).responseImage { (response) -> Void in
guard let image = response.result.value else { return }
cell.img!.image = image
}
}else{
cell.img!.image = UIImage(named: "rad")!
}
cell.nm?.text = sampleArray![indexPath.row]["name"].stringValue
let catarr = sampleArray![indexPath.row]["categories"].array
let des:String! = "category : " + catarr![0]["title"].stringValue + " " + "slug : " + catarr![0]["slug"].stringValue
cell.des?.text = des
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath) as! RecentCellTableViewCell
let sampleArray = self.list.array
let url = sampleArray![indexPath.row]["streams"].array
sendurl = url![0]["stream"].stringValue
self.performSegueWithIdentifier("next", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//
if (segue.identifier == "next") {
// initialize new view controller and cast it as your view controller
var viewController = segue.destinationViewController as! Player
viewController.urll = sendurl
}
}
}
My problem is when i am printing list.arrayvalue.capacity it is showing the actual size of array which is correct but when i tried to print element of array it show's less element then its counting. so i am not sure what is wrong in code????/
The main problem is in printing element. Not printing all elements.
I think you're confusing the array capacity with the actual item count. For numberOfRowsInSection, use the count property of the array instead:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.list.arrayValue.count
}
More details about count vs. capacity in this answer: Swift array.capacity vs array.count

Error subscript

I got that error a while ago and I'm not sure, what's wrong. The Post is just normal custom class with two attributes of type String and int.
web api :http://jsonplaceholder.typicode.com/posts
PostService :
class PostService {
var settings:Settings!
init(){
self.settings = Settings()
}
func getPosts(callback:(NSArray) ->()){
request(settings.viewPost, callback: callback)
}
func request(url:String , callback:(NSArray) ->() ){
let nsURL = NSURL(string: url)
let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL!){(data , repsonse , error) in
//var error:NSError?
do {
let response = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as! NSArray
callback(response)
} catch {
print(error)
}
}
task.resume()
}
}
settings :
import Foundation
class Settings {
var viewPost = "http://jsonplaceholder.typicode.com/posts"
}
post:
class Post {
var _userId:Int
var _title: String
init(userid:Int , title:String){
self._userId = userid
self._title = title
}
func toJSON() ->String{
return ""
}
}
and tableViewController:
class TableViewController: UITableViewController {
var postsCollection = [Post]()
var service:PostService!
override func viewDidLoad() {
super.viewDidLoad()
service = PostService()
service.getPosts{
(response) in
self.loadPosts(response[" "] as! NSArray )
}
}
func loadPosts(posts:NSArray){
for post in posts{
var userId = post["userId"] as! Int
var title = post["title"] as! String
let postObj = Post(userid: userId, title: title)
postsCollection.append(postObj)
dispatch_async(dispatch_get_main_queue()){
self.tableView.reloadData()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return postsCollection.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let post = postsCollection[indexPath.row] as NSData
cell.textLabel?.text = post._userId
cell.detailTextLabel = post._title
return cell
}
why error Cannot subscript a value of type '[Post]' in line
I'm not sure that this is the issue but it is an issue.
Since postsCollection has a distinct type there is no need to cast the type.
NSData is the wrong type anyway.
let post = postsCollection[indexPath.row] // the compiler infers to Post
Side note: Put the dispatch block to reload the table view after the repeat loop to create the Post instances. Reloading the table view in each iteration of the loop is very expensive and not necessary.
for post in posts {
...
}
dispatch_async(dispatch_get_main_queue()){
self.tableView.reloadData()
}
And (public) properties starting with a underscore are pretty unusual (in Swift).
PS: There are two further issues
cell.textLabel?.text = String(post._userId)
cell.detailTextLabel?.text = post._title
Edit: Simple working solution, there are only two classes
class Post
class Post : CustomStringConvertible {
var userId:Int
var title: String
init(userid:Int , title:String){
self.userId = userid
self.title = title
}
var description : String { return String(userId) }
}
class TableViewController
class TableViewController: UITableViewController {
var postsCollection = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://jsonplaceholder.typicode.com/posts")
NSURLSession.sharedSession().dataTaskWithURL(url!){ [unowned self] (data , repsonse , error) in
if error != nil {
print(error!)
} else {
do {
let posts = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as! [[String:AnyObject]]
for post in posts {
let postObj = Post(userid: post["userId"] as! Int, title: post["title"] as! String)
self.postsCollection.append(postObj)
}
dispatch_async(dispatch_get_main_queue()){
self.tableView.reloadData()
}
} catch let error as NSError {
print(error)
}
}
}.resume()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 }
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return postsCollection.count }
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let post = postsCollection[indexPath.row]
cell.textLabel!.text = String(post.userId)
cell.detailTextLabel!.text = post.title
return cell
}
}

How to transfer data from NSArray to String in Swift?

I have to put data in tableview, but even tough I get info from JSON, I can't pass data to postTitle variable. Why is that? Here is my code:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var postTitle = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
var baseURL = "https://hacker-news.firebaseio.com/v0/topstories.json"
// https://hacker-news.firebaseio.com/v0/item/9324191.json
if let url = NSURL(string: baseURL) {
var taskURL = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if error != nil {
println("Error: \(error.localizedDescription)")
} else {
var jsonError: NSError?
if let topStories = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? NSArray {
self.postTitle.append(topStories)
}
}
})
taskURL.resume()
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println(postTitle.count)
return postTitle.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
println(self.postTitle)
// cell.textLabel?.text = postTitle[indexPath.row]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
topStories is an NSArray, but you are appending it to the postTitle array (which is of type [AnyObject]). Array.append adds a single item to the array. So you will have added one entry, an NSArray of a bunch of post IDs, to your postTitle array.
I am guessing what you want is to add the contents of topStories to postTitle? In which case you want to use the extend rather than the append method:
self.postTitle.extend(topStories)
Given that you apparently reload ALL the titles with each request, you could just as easily do this: self.titles = topStories
I just built a test app this way and it worked perfectly fine.
PS: self.postTitle.append would have yielded the wrong result anyway, as it would also append titles you already have in your array. The method you probably should be using would be self.postTitle.join as it uses intersection.
So the other guy from Reddit help me out. I was missing few things. First was data type Int, which needs to be passed to instance variable, and second was UITableView: here is working solution. Hope this will help someone.
import UIKit
class ViewController: UITableViewController, UITableViewDelegate, UITableViewDataSource {
var postTitles = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
var baseURL = "https://hacker-news.firebaseio.com/v0/topstories.json"
if let url = NSURL(string: baseURL) {
var taskURL = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if error != nil {
println("Error: \(error.localizedDescription)")
} else {
var jsonError: NSError?
if let topStories = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? [Int] {
self.postTitles = Array(topStories[0...9])
// Reload the table with our new results!
self.tableView.reloadData()
}
}
})
taskURL.resume()
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postTitles.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
let postTitle = String(self.postTitles[indexPath.row])
cell.textLabel?.text = postTitle
return cell
}
}

Resources