Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- import WebKit
- class ViewController: UITableViewController {
- struct TopStoriesResponse: Decodable {
- let status: String
- let results: [Story]
- }
- struct Story: Decodable {
- let title: String
- let abstract: String
- let url: String
- }
- var headlines = [String]()
- var abstracts = [String]()
- var images = [String]()
- var urls = [URL]()
- var webView: WKWebView!
- override func viewDidLoad() {
- super.viewDidLoad()
- webView = WKWebView()
- getJson { (success) in
- print("Success")
- }
- }
- func getJson(completionHandler: @escaping (Bool) -> ()) {
- let jsonUrlString = "https://api.nytimes.com/svc/topstories/v1/business.json?api-key=f4bf2ee721031a344b84b0449cfdb589:1:73741808"
- guard let url = URL(string: jsonUrlString) else {return}
- URLSession.shared.dataTask(with: url) { (data, response, err) in
- guard let data = data, err == nil else {
- print(err!)
- return
- }
- do {
- let response = try
- JSONDecoder().decode(TopStoriesResponse.self, from: data)
- print(response.results)
- // Pass results into arrays (title, abstract, url, image)
- completionHandler(true)
- DispatchQueue.main.async {
- self.tableView.reloadData()
- }
- } catch let jsonErr {
- print("Error serializing JSON", jsonErr)
- }
- }.resume()
- }
- // MARK: - Tableview methods
- override func numberOfSections(in tableView: UITableView) -> Int {
- return 1
- }
- override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- return headlines.count
- }
- override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let cell = tableView.dequeueReusableCell(withIdentifier: "JSONcell", for: indexPath) as! JSONTableViewCell
- // cell.cellHeadlineLabel.text = self.headlines[indexPath.row]
- // cell.cellDetailLabel.text = self.abstracts[indexPath.row]
- // cell.cellImageView.cacheImage(urlString: self.images[indexPath.row])
- return cell
- }
- override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
- webView.load(URLRequest(url: self.urls[indexPath.row]))
- webView.allowsBackForwardNavigationGestures = true
- view = webView
- // Back button
- // self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.goBack))
- }
- func goBack() {
- if webView.canGoBack {
- webView.goBack()
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement