RepositoriesViewController.swift 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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 RepositoriesViewController: UICollectionViewController, UITextFieldDelegate {
  21. @IBOutlet weak var sortOrderControl: UISegmentedControl!
  22. @IBOutlet weak var searchField: UITextField!
  23. var results: Results<Repository>?
  24. var token: NotificationToken?
  25. deinit {
  26. token?.invalidate()
  27. }
  28. override func viewDidLoad() {
  29. super.viewDidLoad()
  30. let realm = try! Realm()
  31. token = realm.observe { [weak self] _, _ in
  32. self?.reloadData()
  33. }
  34. var components = URLComponents(string: "https://api.github.com/search/repositories")!
  35. components.queryItems = [
  36. URLQueryItem(name: "q", value: "language:objc"),
  37. URLQueryItem(name: "sort", value: "stars"),
  38. URLQueryItem(name: "order", value: "desc")
  39. ]
  40. URLSession.shared.dataTask(with: URLRequest(url: components.url!)) { data, _, error in
  41. if let error = error {
  42. print(error)
  43. return
  44. }
  45. do {
  46. let repositories = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: AnyObject]
  47. let items = repositories["items"] as! [[String: AnyObject]]
  48. let realm = try Realm()
  49. try realm.write {
  50. for item in items {
  51. let repository = Repository()
  52. repository.identifier = String(item["id"] as! Int)
  53. repository.name = item["name"] as? String
  54. repository.avatarURL = item["owner"]!["avatar_url"] as? String
  55. realm.add(repository, update: .modified)
  56. }
  57. }
  58. } catch {
  59. print(error.localizedDescription)
  60. }
  61. }.resume()
  62. }
  63. override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  64. return results?.count ?? 0
  65. }
  66. override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  67. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! RepositoryCell
  68. let repository = results![indexPath.item]
  69. cell.titleLabel.text = repository.name
  70. URLSession.shared.dataTask(with: URLRequest(url: URL(string: repository.avatarURL!)!)) { (data, _, error) -> Void in
  71. if let error = error {
  72. print(error.localizedDescription)
  73. return
  74. }
  75. DispatchQueue.main.async {
  76. let image = UIImage(data: data!)!
  77. cell.avatarImageView!.image = image
  78. }
  79. }.resume()
  80. return cell
  81. }
  82. func reloadData() {
  83. let realm = try! Realm()
  84. results = realm.objects(Repository.self)
  85. if let text = searchField.text, !text.isEmpty {
  86. results = results?.filter("name contains[c] %@", text)
  87. }
  88. results = results?.sorted(byKeyPath: "name", ascending: sortOrderControl!.selectedSegmentIndex == 0)
  89. collectionView?.reloadData()
  90. }
  91. @IBAction func valueChanged(sender: AnyObject) {
  92. reloadData()
  93. }
  94. @IBAction func clearSearchField(sender: AnyObject) {
  95. searchField.text = nil
  96. reloadData()
  97. }
  98. func textFieldDidEndEditing(_ textField: UITextField) {
  99. reloadData()
  100. }
  101. }