-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathRepositoriesViewController.swift
121 lines (101 loc) · 4.15 KB
/
RepositoriesViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import UIKit
import RealmSwift
class RepositoriesViewController: UICollectionViewController, UITextFieldDelegate {
@IBOutlet weak var sortOrderControl: UISegmentedControl!
@IBOutlet weak var searchField: UITextField!
var results: Results<Repository>?
var token: NotificationToken?
deinit {
token?.invalidate()
}
override func viewDidLoad() {
super.viewDidLoad()
let realm = try! Realm()
token = realm.observe { [weak self] _, _ in
self?.reloadData()
}
var components = URLComponents(string: "https://api.github.com/search/repositories")!
components.queryItems = [
URLQueryItem(name: "q", value: "language:objc"),
URLQueryItem(name: "sort", value: "stars"),
URLQueryItem(name: "order", value: "desc")
]
URLSession.shared.dataTask(with: URLRequest(url: components.url!)) { data, _, error in
if let error = error {
print(error)
return
}
do {
let repositories = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: AnyObject]
let items = repositories["items"] as! [[String: AnyObject]]
let realm = try Realm()
try realm.write {
for item in items {
let repository = Repository()
repository.identifier = String(item["id"] as! Int)
repository.name = item["name"] as? String
repository.avatarURL = item["owner"]!["avatar_url"] as? String
realm.add(repository, update: .modified)
}
}
} catch {
print(error.localizedDescription)
}
}.resume()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return results?.count ?? 0
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! RepositoryCell
let repository = results![indexPath.item]
cell.titleLabel.text = repository.name
URLSession.shared.dataTask(with: URLRequest(url: URL(string: repository.avatarURL!)!)) { (data, _, error) -> Void in
if let error = error {
print(error.localizedDescription)
return
}
DispatchQueue.main.async {
let image = UIImage(data: data!)!
cell.avatarImageView!.image = image
}
}.resume()
return cell
}
func reloadData() {
let realm = try! Realm()
results = realm.objects(Repository.self)
if let text = searchField.text, !text.isEmpty {
results = results?.filter("name contains[c] %@", text)
}
results = results?.sorted(byKeyPath: "name", ascending: sortOrderControl!.selectedSegmentIndex == 0)
collectionView?.reloadData()
}
@IBAction func valueChanged(sender: AnyObject) {
reloadData()
}
@IBAction func clearSearchField(sender: AnyObject) {
searchField.text = nil
reloadData()
}
func textFieldDidEndEditing(_ textField: UITextField) {
reloadData()
}
}