-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHomeViewController.swift
More file actions
372 lines (302 loc) · 14.4 KB
/
HomeViewController.swift
File metadata and controls
372 lines (302 loc) · 14.4 KB
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
//
// HomeViewController.swift
// Cluster
//
// Created by lsecrease on 8/19/15.
// Copyright (c) 2015 ImagineME. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
//MARK: - IBOutlets
@IBOutlet weak var backgroundImageView:PFImageView!
@IBOutlet weak var collectionView:UICollectionView!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var klusterTitle: UILabel!
@IBOutlet weak var searchButton: UIButton!
@IBOutlet weak var menuButton: UIButton!
@IBOutlet weak var currentUserProfileImageButton:UIButton!
@IBOutlet var createKlusterButton: UIButton!
//MARK: - UICollectionViewDataSource
private var klusters = [PFObject]()
var locationManager = CLLocationManager()
var currentGeoPoint: PFGeoPoint?
var userProfileView: ProfileNameView?
//MARK: - Change Status Bar to White
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
override func viewDidLoad() {
super.viewDidLoad()
let latitude = LocationStore.sharedStore.currentLatitude()
let longitude = LocationStore.sharedStore.currentLongitude()
self.currentGeoPoint = PFGeoPoint.init(latitude: latitude, longitude: longitude)
// Hide search bar and cancel button
self.searchBar.hidden = true
self.cancelButton.hidden = true
// Set delegates
self.locationManager.delegate = self
self.searchBar.delegate = self;
// Add a tap recognizer to dismiss the keyboard when the searchbar is active
let tapRecognizer = UITapGestureRecognizer.init(target: self, action: "viewTapped:")
self.view.addGestureRecognizer(tapRecognizer)
self.calculateCurrentLocation()
self.addProfileView()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
// Hack to set search bar text color to white..
UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).textColor = .whiteColor()
self.fetchKlusters()
let authorizationStatus = CLLocationManager.authorizationStatus()
let locationAuthorized = authorizationStatus == .AuthorizedWhenInUse
self.createKlusterButton.enabled = locationAuthorized
if (locationAuthorized) {
self.locationManager.startUpdatingLocation()
} else {
// let's request location authorization
self.locationManager.requestWhenInUseAuthorization()
}
self.updateUserInfo()
}
private func showLogin() {
let storyboard = UIStoryboard.init(name: "Login", bundle: nil)
let loginVC = storyboard.instantiateViewControllerWithIdentifier("LoginViewController") as! LoginViewController
self.presentViewController(loginVC, animated: true, completion: nil)
}
private func calculateCurrentLocation() {
PFGeoPoint.geoPointForCurrentLocationInBackground({ (geoPoint, error) -> Void in
if (error == nil) {
self.currentGeoPoint = geoPoint
if let geoPoint = geoPoint {
LocationStore.sharedStore.updateLocation(geoPoint.latitude, longitude: geoPoint.longitude)
}
}
})
}
@IBAction func cancelButtonPressed(sender: AnyObject) {
self.searchBar.resignFirstResponder()
self.updateUIForSearch(false)
}
@IBAction func searchButtonPressed(sender: AnyObject) {
self.updateUIForSearch(true)
// Make searchbar the first responder
self.searchBar.becomeFirstResponder()
}
func viewTapped(sender: UITapGestureRecognizer) {
if (self.searchBar.isFirstResponder()) {
self.searchBar.resignFirstResponder()
self.updateUIForSearch(false)
}
}
private func updateUIForSearch(searching: Bool) {
// Unhide search bar & cancel button
self.searchBar.hidden = !searching
self.cancelButton.hidden = !searching
// Unhide cancel button
self.searchBar.hidden = !searching
// Hide search button & label
self.searchButton.hidden = searching
self.klusterTitle.hidden = searching
}
private func fetchKlusters() {
var params = [:]
if let geoPoint = self.currentGeoPoint {
params = ["latitude" : geoPoint.latitude,
"longitude" : geoPoint.longitude]
}
KlusterDataSource.fetchMainKlusters(params as [NSObject : AnyObject]) { (objects, error) -> Void in
if let error = error {
print("Error: %@", error.localizedDescription)
} else {
self.klusters = objects as! [PFObject]
self.collectionView.reloadData()
self.updateBackground(self.klusters.first)
}
}
}
private func updateBackground(object: PFObject?) {
if let object = object {
let k = Kluster.init(object: object)
self.backgroundImageView.file = k.featuredImageFile
self.backgroundImageView.loadInBackground()
}
}
/**
Updates the bottom-right view of the user
We call this when the view appears in case a user
changes their name or avatar.
**/
private func updateUserInfo() {
self.userProfileView?.layoutForUser(PFUser.currentUser())
}
private func addProfileView() {
let user = PFUser.currentUser()
let firstName = user?.objectForKey("firstName") as? String
let maxWidth = self.view.frame.size.width - 200.0
let font = UIFont.systemFontOfSize(17)
let labelWidth = self.widthForlabel(firstName, font: font, maxWidth: maxWidth)
let profileFrame = CGRectMake(0, 0, labelWidth, 40)
self.userProfileView = ProfileNameView.init(frame: profileFrame)
if let userProfileView = self.userProfileView {
userProfileView.layoutForUser(user)
self.view.addSubview(userProfileView)
let profileRecognizer = UITapGestureRecognizer.init(target: self, action: "profileTapped:")
userProfileView.addGestureRecognizer(profileRecognizer)
let metrics = ["spacing" : 6]
let views = ["userProfileView" : userProfileView]
let profileH = NSLayoutConstraint.constraintsWithVisualFormat("H:[userProfileView]-|", options: NSLayoutFormatOptions(rawValue: 0) , metrics: nil, views: views)
let profileY = NSLayoutConstraint.constraintsWithVisualFormat("V:[userProfileView]-(spacing)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics , views: views)
self.view.addConstraints(profileH)
self.view.addConstraints(profileY)
}
}
private func widthForlabel(text: String?, font: UIFont, maxWidth: CGFloat) -> CGFloat {
let label:UILabel = UILabel(frame: CGRectMake(0, 0, maxWidth, CGFloat.max))
label.numberOfLines = 1
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
func profileTapped(sender: UITapGestureRecognizer) {
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let profileController = storyboard.instantiateViewControllerWithIdentifier("ProfileViewController")
self.presentViewController(profileController, animated: true, completion: nil)
}
}
extension HomeViewController : UICollectionViewDataSource
{
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.klusters.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cellIdentifier = "Kluster Cell"
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! KlusterCollectionViewCell
let k = Kluster.init(object: self.klusters[indexPath.item])
cell.kluster = k
cell.joinKlusterButton.tag = indexPath.row
cell.joinKlusterButton.addTarget(self, action: "joinKluster:", forControlEvents: UIControlEvents.TouchUpInside)
cell.joinKlusterButton.hidden = KlusterStore.sharedInstance.userIsMemberOfKluster(k.id)
cell.distanceLabel.text = k.distanceToKluster(self.currentGeoPoint)
// Moved the PFImageView loading out of the cell
cell.featuredImageView.tag = indexPath.row
cell.featuredImageView.image = nil
cell.featuredImageView.file = k.featuredImageFile
cell.featuredImageView.loadInBackground { (image, error) -> Void in
if (error != nil) {
print("Error loading image...")
} else {
print("Finished loading image...")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
cell.featuredImageView.image = image
});
}
}
// Load avatar images
let avatarImageViews = [cell.firstAvatarImageView, cell.secondAvatarImageView, cell.thirdAvatarImageView, cell.fourthAvatarImageView]
let membersQuery = k.memberRelation.query()
membersQuery.cachePolicy = .CacheElseNetwork
membersQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
var totalAvatars = 4
if (objects?.count < avatarImageViews.count) {
totalAvatars = objects!.count
}
if (objects!.count > 4) {
let moreCount = objects!.count - 4
let buttonText = "\(moreCount) more..."
cell.moreLabel .setTitle(buttonText, forState: .Normal)
cell.moreLabel.hidden = false
} else {
cell.moreLabel.hidden = true
}
// Clear the image views...
for imageView in avatarImageViews {
imageView.image = nil
}
var i = 0
while i < totalAvatars {
let imageView = avatarImageViews[i]
let user = objects![i] as? PFUser
imageView?.file = user?.objectForKey("avatarThumbnail") as? PFFile
imageView?.loadInBackground()
i++
imageView.layer.cornerRadius = 12.5
}
}
let tapRecognizer = UITapGestureRecognizer.init(target: self, action: "featuredImageViewTapped:")
cell.featuredImageView.addGestureRecognizer(tapRecognizer)
return cell
}
func featuredImageViewTapped(sender: UITapGestureRecognizer) {
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let messagesController = storyboard.instantiateViewControllerWithIdentifier("MessagesTableViewController") as! MessagesTableViewController
let k = Kluster.init(object: self.klusters[(sender.view?.tag)!])
messagesController.kluster = k
// Show kluster
let navigationController = MessagesNavigationController.init(rootViewController: messagesController)
self.presentViewController(navigationController, animated: true, completion: nil);
}
func joinKluster(sender: UIButton) {
let k = Kluster.init(object: self.klusters[sender.tag])
let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
KlusterDataSource.joinKluster(k.id) { (object, error) -> Void in
hud.removeFromSuperview()
if (error != nil) {
print("Error: %@", error)
} else {
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let klusterVC = storyboard.instantiateViewControllerWithIdentifier("KlusterViewController") as! KlusterViewController;
klusterVC.kluster = k
// Show kluster
let navigationController = UINavigationController.init(rootViewController: klusterVC)
self.presentViewController(navigationController, animated: true, completion: nil);
}
}
}
}
extension HomeViewController : CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if (status == .AuthorizedWhenInUse) {
self.calculateCurrentLocation()
}
}
}
//MARK: - Scrolling Experience
extension HomeViewController : UIScrollViewDelegate
{
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let layout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
let cellWidthIncludingSpacing = layout.itemSize.width + layout.minimumLineSpacing
var offset = targetContentOffset.memory
let index = (offset.x + scrollView.contentInset.left) / cellWidthIncludingSpacing
let roundedIndex = round(index)
offset = CGPoint(x: roundedIndex * cellWidthIncludingSpacing - scrollView.contentInset.left, y: -scrollView.contentInset.top)
targetContentOffset.memory = offset
}
}
// MARK: - Search delegate
extension HomeViewController : UISearchBarDelegate {
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
let searchString = searchText.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if searchString.length > 0 {
KlusterDataSource.searchForKlusterWithString(searchString) { (objects, error) -> Void in
if (error != nil) {
print("Error: %@", error?.localizedDescription)
} else {
self.klusters = objects as! [PFObject]
self.collectionView.reloadData()
}
}
}
}
func searchBarShouldEndEditing(searchBar: UISearchBar) -> Bool {
// Hide search bar...
self.searchBar.resignFirstResponder()
return true
}
}