Created
August 28, 2016 19:41
-
-
Save alonecuzzo/54c53330888d8f955ffbc8a9abe7fb39 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// Brews | |
// | |
// Created by Jabari Bell on 8/28/16. | |
// Copyright © 2016 codemitten. All rights reserved. | |
// | |
import UIKit | |
import Alamofire | |
import SwiftyJSON | |
class ViewController: UIViewController { | |
//MARK: Property | |
let tableView = UITableView(frame: .zero) | |
let CellIdentifier = "LOL" | |
var beers = [Beer]() | |
//MARK: Method | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
setupTableView() | |
} | |
override func viewDidAppear(animated: Bool) { | |
super.viewDidAppear(animated) | |
fetchBeers { beers in | |
self.beers = beers | |
dispatch_async(dispatch_get_main_queue(),{ | |
self.tableView.reloadData() | |
}) | |
} | |
} | |
private func setupTableView() { | |
view.addSubview(tableView) | |
tableView.dataSource = self | |
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: CellIdentifier) | |
} | |
override func viewDidLayoutSubviews() { | |
super.viewDidLayoutSubviews() | |
tableView.frame = view.bounds | |
} | |
} | |
//MARK: UITableViewDataSource | |
extension ViewController: UITableViewDataSource { | |
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return beers.count | |
} | |
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) | |
cell.textLabel?.text = beers[indexPath.row].name | |
return cell | |
} | |
} | |
//MARK: Network/Data Layer | |
extension ViewController { | |
private func fetchBeers(onCompletion: ([Beer] -> Void)) { | |
var internalBrews = [Beer]() | |
let url = "http://api.brewerydb.com/v2/menu/styles?key=42473b9531e8ae8aba74622ef4fab78b&format=json" | |
Alamofire.request(.GET, url).responseJSON { response in | |
guard let value = response.result.value else { return } | |
let json = JSON(value) | |
for (_, obj) in json["data"] { | |
internalBrews.append(Beer(name: obj["name"].stringValue)) | |
} | |
onCompletion(internalBrews) | |
} | |
} | |
} | |
//MARK: Beer model - add more properties | |
struct Beer { | |
let name: String | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment