Skip to content

Instantly share code, notes, and snippets.

@kalub92
Created October 17, 2018 23:19
Show Gist options
  • Save kalub92/a0fe5894f67626dae933b17ce32c2df3 to your computer and use it in GitHub Desktop.
Save kalub92/a0fe5894f67626dae933b17ce32c2df3 to your computer and use it in GitHub Desktop.
A search ViewController from a meal planning app I'm working on in my spare time.
//
// SearchVC.swift
// Meals
//
// Created by Caleb Stultz on 9/26/18.
// Copyright © 2018 Caleb Stultz. All rights reserved.
//
/*
Code is from a collaborative meal planning app I'm building. This ViewController allows a user to enter an ingredient as a search query into a UISearchBar instance and search for recipes with that ingredient present. Each UITableViewCell has an image of type CustomImageView that allows for synchronous image caching/loading in the background.
*/
import UIKit
import SafariServices
class SearchVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UITextFieldDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var spinner: UIActivityIndicatorView!
var recipes: [Recipe] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
searchBar.delegate = self
searchBar.becomeFirstResponder()
spinner.isHidden = true
}
@IBAction func dismiss(_ sender: Any) {
searchBar.resignFirstResponder()
dismiss(animated: true, completion: nil)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
guard let query = searchBar.text else { return }
if query != "" {
spinner.isHidden = false
spinner.startAnimating()
searchBar.resignFirstResponder()
NetworkManager.searchRecipes(withQuery: query) { (recipes) in
self.recipes = recipes
DispatchQueue.main.async {
self.tableView.reloadData()
self.spinner.stopAnimating()
self.spinner.isHidden = true
}
}
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText == "" {
recipes = []
tableView.reloadData()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "recipeCell", for: indexPath) as? RecipeCell else { return UITableViewCell() }
cell.configureCell(recipe: recipes[indexPath.row])
cell.foodImageView.loadImage(fromURLString: recipes[indexPath.row].imageURLString)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let sourceUrl = URL(string: recipes[indexPath.row].sourceURLString) else { return }
let vc = SFSafariViewController(url: sourceUrl)
present(vc, animated: true, completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment