Skip to content

Instantly share code, notes, and snippets.

@rtking1993
Created April 8, 2018 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rtking1993/37f0c3faadaf75d271873f845ab9235e to your computer and use it in GitHub Desktop.
Save rtking1993/37f0c3faadaf75d271873f845ab9235e to your computer and use it in GitHub Desktop.
View Controller for showing a list of New York Times articles
// MARK: Frameworks
import UIKit
// MARK: ArticleViewController
class ArticleViewController: UIViewController {
// MARK: Outlets
@IBOutlet var myTableView: UITableView!
// MARK: Variables
var articles: [Article] = []
// MARK: View Methods
override func viewDidLoad() {
super.viewDidLoad()
ArticleRemote.retrieveArticles { articles in
self.articles = articles.results
DispatchQueue.main.async {
self.myTableView.reloadData()
}
}
}
}
// MARK: UITableViewDataSource Methods
extension ArticleViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return articles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
let article = articles[indexPath.row]
cell.textLabel?.text = article.title
return cell
}
}
// MARK: UITableViewDelegate Methods
extension ArticleViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let article = articles[indexPath.row]
openURL(article.url)
}
// MARK: Helper Methods
private func openURL(_ url: URL) {
guard UIApplication.shared.canOpenURL(url) == true else {
return
}
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment