-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPhotosVC.swift
243 lines (170 loc) · 8.22 KB
/
PhotosVC.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
//
// PinVC.swift
// VirtualTourist-iOS
//
// Created by Michael Alexander on 6/26/17.
// Copyright © 2017 Michael Alexander. All rights reserved.
//
import Foundation
import MapKit
import UIKit
import CoreData
class PhotosVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource{
var pin: Pin!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var photoCollectionView: UICollectionView!
@IBOutlet weak var newCollectionBtn: UIButton!
fileprivate let cellsPerRow: CGFloat = 3
fileprivate let sectionInsets = UIEdgeInsets(top: 50.0, left: 20.0, bottom: 50.0, right: 20.0)
var noPhotosLabel = UILabel()
lazy var fetchedResultsController: NSFetchedResultsController <Photo> = {
let delegate = UIApplication.shared.delegate as! AppDelegate
let stack = delegate.stack
let fr = NSFetchRequest<NSFetchRequestResult>(entityName: "Photo")
fr.sortDescriptors = []
let predicate = NSPredicate(format: "pin = %@", self.pin)
fr.predicate = predicate
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fr, managedObjectContext: stack.context, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController.delegate = self
return fetchedResultsController as! NSFetchedResultsController<Photo>
}()
override func viewDidLoad() {
super.viewDidLoad()
photoCollectionView.allowsMultipleSelection = true
addPinToView()
performUIUpdatesOnMain { self.noPhotosLabel = self.configNoPhotosLabel()}
fetchPhotos()
performUIUpdatesOnMain { self.photoCollectionView.reloadData() }
photoCollectionView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.old, context: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
photoCollectionView.removeObserver(self, forKeyPath: "contentSize")
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let observedObject = object as? UICollectionView, observedObject == photoCollectionView {
//collection view is done loading
performUIUpdatesOnMain {
self.newCollectionBtn.isEnabled = true
}
}
}
func fetchPhotos() {
do {
try fetchedResultsController.performFetch()
} catch {
print("Unable to retrieve Photos\nPlease try again.")
}
}
public func addPinToView() {
let lat = CLLocationDegrees(pin.latitude)
let long = CLLocationDegrees(pin.longitude)
let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
mapView.addAnnotation(annotation)
let span = MKCoordinateSpanMake(0.5, 0.5)
let region = MKCoordinateRegion(center: annotation.coordinate, span: span)
mapView.setRegion(region, animated: true)
}
public func configNoPhotosLabel()-> UILabel{
let label = UILabel()
label.text = "No photos found for this location."
label.isHidden = true
label.frame = CGRect(x:self.view.frame.size.width/10,y: self.view.frame.size.height/2,width: 300,height: 60)
self.view.addSubview(label)
return label
}
public func deletePhotoCollection() {
for index in fetchedResultsController.fetchedObjects!{
fetchedResultsController.managedObjectContext.delete(index as NSManagedObject)
do {
try fetchedResultsController.managedObjectContext.save()
} catch {
print("There was an error saving")
}
}
}
@IBAction func newCollectionPressed(_ sender: Any) {
deletePhotoCollection()
pin.isDownloaded = false
FlickrClient.sharedInstance().getPhotosForPin(pin: pin)
pin.isDownloaded = true
print(pin.isDownloaded)
performUIUpdatesOnMain {
self.photoCollectionView.reloadData()
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let sections = fetchedResultsController.sections![section]
if sections.numberOfObjects == 0{
performUIUpdatesOnMain { self.noPhotosLabel.isHidden = false }
}else{
performUIUpdatesOnMain { self.noPhotosLabel.isHidden = true }
}
return sections.numberOfObjects
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let delegate = UIApplication.shared.delegate as! AppDelegate
let stack = delegate.stack
let cell = photoCollectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! PhotoCollectionViewCell
let photo = fetchedResultsController.object(at: indexPath)
if let imageData = photo.imageData {
let image = UIImage(data: imageData as Data)
performUIUpdatesOnMain {
cell.placeHolderView.isHidden = true
cell.photoImageView.image = image
}
}else{
performUIUpdatesOnMain {
self.newCollectionBtn.isEnabled = false
cell.activityIndicator.startAnimating()
cell.placeHolderView.isHidden = false
}
FlickrClient.sharedInstance().loadPhotoFromURL(imagePath: photo.imageURL!) { (imageData, error) in
guard error == nil else {
print("Error loading photo from URL-\(error)"); return}
photo.imageData = imageData as NSData?
stack.save()
self.performUIUpdatesOnMain {
cell.activityIndicator.hidesWhenStopped = true
cell.activityIndicator.stopAnimating()
}
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
fetchedResultsController.managedObjectContext.delete(fetchedResultsController.object(at: indexPath) as NSManagedObject)
do {
try fetchedResultsController.managedObjectContext.save()
} catch {
print("Error saving photos")
}
}
}
extension PhotosVC: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize {
let totalPadding = sectionInsets.left * (cellsPerRow + 1)
let availableWidth = view.frame.width - totalPadding
let widthPerItem = availableWidth / cellsPerRow
return CGSize(width: widthPerItem, height: widthPerItem)
}
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return sectionInsets
}
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return sectionInsets.left
}
}
extension PhotosVC: NSFetchedResultsControllerDelegate {
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert: photoCollectionView.insertItems(at: [newIndexPath!])
case .delete: photoCollectionView.deleteItems(at: [indexPath!])
case .update: photoCollectionView.reloadItems(at: [indexPath!])
default:
return
}
}
}