Skip to content

Instantly share code, notes, and snippets.

@soxjke
Created February 9, 2020 18:06
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 soxjke/96a44be0467537cf74d270cd16dc7531 to your computer and use it in GitHub Desktop.
Save soxjke/96a44be0467537cf74d270cd16dc7531 to your computer and use it in GitHub Desktop.
import UIKit
class ViewController: UIViewController {
private(set) var data: [GithubAPI.Response.Model] = []
private(set) var searchTerm: String = ""
@IBOutlet private var tableView: UITableView!
@IBOutlet private var searchField: UITextField!
@IBOutlet private var errorLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
searchField.addTarget(self, action: #selector(textDidChange(_:)), for: .editingChanged)
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "GithubRepoCell", for: indexPath)
cell.textLabel?.text = data[indexPath.row].full_name
cell.detailTextLabel?.text = "⭐️ \(data[indexPath.row].stargazers_count)"
return cell
}
}
extension ViewController {
@objc func textDidChange(_ sender: UITextField) {
searchTerm = sender.text ?? ""
GithubAPI.search(term: searchTerm) { [weak self] result in
switch (result) {
case .success(let models): self?.onSuccess(models)
case .failure(let error): self?.onError(error)
}
}
}
private func onSuccess(_ models: [GithubAPI.Response.Model]) {
DispatchQueue.main.async {
self.data = models
self.tableView.reloadData()
}
}
private func onError(_ error: Error) {
DispatchQueue.main.async {
self.errorLabel.text = (error as NSError).localizedDescription
self.errorLabel.isHidden = false
DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in
self?.errorLabel.isHidden = true
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment