-
Notifications
You must be signed in to change notification settings - Fork 0
/
ActiveRideRequestsTableVC.swift
319 lines (227 loc) · 12.1 KB
/
ActiveRideRequestsTableVC.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
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
//
// ActiveRideRequestsTableVC.swift
// uberClone
//
// Created by Doug Wells on 2/13/17.
// Copyright © 2017 Parse. All rights reserved.
//
import UIKit
import Parse
import MapKit
import Foundation
class ActiveRideRequestsTableVC: UITableViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
var requestUsernames = [String]()
var requestUserIds = [String]()
var requestObjectIds = [String]()
var requestLocations = [PFGeoPoint]()
@IBAction func tableToMap(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "tableToMap", sender: self)
}
@IBAction func updateTable(_ sender: UIBarButtonItem) {
updateActiveRideRequestsTable()
}
@IBAction func logout(_ sender: Any) {
print("Logging out \(PFUser.current()?.username).")
PFUser.logOutInBackground(block: { (error) in
if error != nil {
print("error logging out user \(PFUser.current()?.username)")
} else {
print("logged out user \(PFUser.current()?.username)")
self.navigationController?.navigationBar.isHidden = true
//self.navigationController?.toolbar.isHidden = true
self.navigationController?.setToolbarHidden(true, animated: false)
self.locationManager.stopUpdatingLocation()
self.performSegue(withIdentifier: "activeRideReqTableToLogin", sender: self)
}
})
}
func createAlert(title: String, message: String ) {
//creat alert
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
//add button to alert
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
//present alert
self.present(alert, animated: true, completion: nil)
} //End createAlert
override func viewDidAppear(_ animated: Bool) {
updateActiveRideRequestsTable()
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setToolbarHidden(false, animated: false)
self.navigationController?.setNavigationBarHidden(false, animated: false)
updateActiveRideRequestsTable()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
locationManager.delegate = self //sets delegate to VC so VC can control it
locationManager.desiredAccuracy = kCLLocationAccuracyBest //several accuracies avail.
locationManager.requestWhenInUseAuthorization()
// Uncomment if want auto-update of table (~ every 2 seconds)
//locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
updateActiveRideRequestsTable()
/* Using CLLocation to find driver's position
if let location = manager.location?.coordinate {
let driverGeoPoint = PFGeoPoint(latitude: location.latitude, longitude: location.longitude)
let query = PFQuery(className: "RiderRequest")
query.whereKey("location", nearGeoPoint: driverGeoPoint )
query.limit = 10
requestUsernames.removeAll()
requestObjectIds.removeAll()
query.findObjectsInBackground(block: { (objects, error) in
if let riderRequests = objects {
for riderRequest in riderRequests {
let requestId = riderRequest.objectId
let riderName = riderRequest["username"]
let riderId = riderRequest["userId"]
let riderLocation = riderRequest["location"] as? PFGeoPoint
let distance = riderLocation?.distanceInMiles(to: driverGeoPoint)
self.requestUsernames.append(riderName as! String)
self.requestObjectIds.append(requestId! as String)
print("Username", riderName)
}
}
self.tableView.reloadData()
})
}
*/
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //activate Segue to secondView
print("indexPath = ", indexPath.row)
//performSegue(withIdentifier: "tableToDirections", sender: nil)
let message = self.requestUsernames[indexPath.row]
let messageArr = message.components(separatedBy: "|")
let name = messageArr[0]
let objectId = self.requestObjectIds[indexPath.row]
let geopoint = self.requestLocations[indexPath.row]
let latitude = geopoint.latitude
let longitude = geopoint.longitude
let acceptRideAlert = UIAlertController(title: "Accept ride request from \(name)?", message: "Press OK to accept & to obtain directions to pickup location", preferredStyle: UIAlertControllerStyle.alert)
acceptRideAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
acceptRideAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: {(action) in
self.getDirections(latitude: latitude, longitude: longitude, name: name )
let query = PFQuery(className: "RiderRequest")
query.whereKey("objectId", equalTo: objectId)
query.findObjectsInBackground(block: { (objects, error) in
if let riderRequests = objects {
for riderRequest in riderRequests {
riderRequest["driverAccepted"] = PFUser.current()?.username
riderRequest.saveInBackground()
}
}
})
acceptRideAlert.dismiss(animated: true, completion: nil)
}))
present(acceptRideAlert, animated: true, completion: nil)
}
func getDirections (latitude: CLLocationDegrees, longitude: CLLocationDegrees, name: String) {
let requestCLLocation = CLLocation(latitude: latitude, longitude: longitude)
CLGeocoder().reverseGeocodeLocation(requestCLLocation, completionHandler: { (placemarks, error) in
if let placemarks = placemarks {
if placemarks.count > 0 {
let mKPlacemark = MKPlacemark(placemark: placemarks[0])
let mapItem = MKMapItem(placemark: mKPlacemark)
mapItem.name = name
let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving]
mapItem.openInMaps(launchOptions: launchOptions)
}
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateActiveRideRequestsTable() {
PFGeoPoint.geoPointForCurrentLocation { (geopoint, error) in
if let driverGeoPoint = geopoint {
let query = PFQuery(className: "RiderRequest")
query.whereKey("driverAccepted", equalTo: "Not yet accepted")
query.whereKey("location", nearGeoPoint: driverGeoPoint )
query.limit = 10
self.requestUsernames.removeAll()
self.requestUserIds.removeAll()
self.requestObjectIds.removeAll()
self.requestLocations.removeAll()
query.findObjectsInBackground(block: { (objects, error) in
if let riderRequests = objects {
if riderRequests.count > 0 {
for riderRequest in riderRequests {
let requestId = riderRequest.objectId
let riderId = riderRequest["userId"] as? String
let riderLocation = riderRequest["location"] as? PFGeoPoint
let distance = riderLocation!.distanceInMiles(to: driverGeoPoint)
let distanceString = String(format: "%.2f miles", distance)
let riderName = riderRequest["username"]! as! String
let riderNameArr = riderName.components(separatedBy: "-")
let riderMessage = "\(riderNameArr[1]) | Distance: \(distanceString)"
self.requestUsernames.append(riderMessage)
self.requestObjectIds.append(requestId! as String)
self.requestLocations.append(riderLocation!)
//print("Username", riderName)
}
}
}
self.tableView.reloadData()
})
}
}
} //end updateUberPickupLocation
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return requestUsernames.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
// Configure the cell...
cell.textLabel?.text = requestUsernames[indexPath.row]
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}