PlacesViewController.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2014 Realm Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. ////////////////////////////////////////////////////////////////////////////
  18. import UIKit
  19. import RealmSwift
  20. class PlacesViewController: UITableViewController, UITextFieldDelegate {
  21. @IBOutlet weak var searchField: UITextField!
  22. var results: Results<Place>?
  23. override func viewDidLoad() {
  24. super.viewDidLoad()
  25. let seedFileURL = Bundle.main.url(forResource: "Places", withExtension: "realm")
  26. let config = Realm.Configuration(fileURL: seedFileURL, readOnly: true)
  27. Realm.Configuration.defaultConfiguration = config
  28. reloadData()
  29. }
  30. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  31. return results?.count ?? 0
  32. }
  33. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  34. let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
  35. let place = results![indexPath.row]
  36. cell.textLabel!.text = place.postalCode
  37. cell.detailTextLabel!.text = "\(place.placeName!), \(place.state!)"
  38. if let county = place.county {
  39. cell.detailTextLabel!.text = cell.detailTextLabel!.text! + ", \(county)"
  40. }
  41. return cell
  42. }
  43. func reloadData() {
  44. let realm = try! Realm()
  45. results = realm.objects(Place.self)
  46. if let text = searchField.text, !text.isEmpty {
  47. results = results?.filter("postalCode beginswith %@", text)
  48. }
  49. results = results?.sorted(byKeyPath: "postalCode")
  50. tableView?.reloadData()
  51. }
  52. func textFieldDidEndEditing(_ textField: UITextField) {
  53. reloadData()
  54. }
  55. }