I'm building a very basic reddit client for iPhone, just to practice developing for iOS. I've gotten it to parse the JSON of my selected subreddit, however I'm unable to take the titles from the parsed JSON and display them in my UITableView. The problem I'm having at the moment is that I can't get my "postList" array to populate with the JSON data before the UITableView is loaded. So when the table views cells are being populated, there's nothing in the postList array's elements for them to be populated with. Any idea how to fix this?
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
let URL = "https://www.reddit.com/r/swift/.json"
var postList : [PostList] = Array(repeating: PostList(), count: 26)
//var postList : [PostList] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.dataSource = self
tableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Setting up tableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "aroundMeCell", for: indexPath)
getPosts(url: URL, row: indexPath.row, cell: cell)
let title = postList[indexPath.row].title
cell.textLabel?.text = title
return cell
}
//Receiving posts using Alamofire
func getPosts(url: String, row: Int, cell: UITableViewCell) {
Alamofire.request(url, method: .get)
.responseJSON { response in
if response.result.isSuccess {
let postJSON : JSON = JSON(response.result.value!)
//print(postJSON)
self.createPostListArray(json: postJSON, row: row, cell: cell)
} else {
print("Error: \(String(describing: response.result.error)) aaaaaa")
}
}
}
func createPostListArray(json: JSON, row: Int, cell: UITableViewCell) {
let titlePath : [JSONSubscriptType] = ["data", "children", row, "data", "title"]
let postPath : [JSONSubscriptType] = ["data", "children", row, "data", "selftext"]
//Making sure I can unwrap both
if(json[titlePath].string != nil && json[postPath].string != nil){
let inTitle = json[titlePath].string!
let inPost = json[postPath].string!
postList[row].title = inTitle
postList[row].post = inPost
}
else{
print("error")
}
}
Array(repeating:count:
syntax. Declare the array emptyvar postList = [PostList]()
and append or insert the items. And do not populate the data source array incellForRowAt
, do it inviewDidLoad
.