-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapViewController.swift
More file actions
367 lines (250 loc) · 11.7 KB
/
MapViewController.swift
File metadata and controls
367 lines (250 loc) · 11.7 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
//
// MapViewController.swift
// WhereAmI
//
// Created by Sergey Leskov on 2/6/17.
// Copyright © 2017 Sergey Leskov. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
import UserNotifications
import CoreData
class MapViewController: UIViewController {
//==================================================
// MARK: - Stored Properties
//==================================================
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var stopButton: UIButton!
@IBOutlet weak var addPointButton: UIButton!
@IBOutlet weak var saveButton: UIButton!
lazy var locationManager: CLLocationManager = {
var _locationManager = CLLocationManager()
_locationManager.delegate = self
//_locationManager.requestWhenInUseAuthorization()
_locationManager.requestAlwaysAuthorization() //for Background
// We want the best and the most precise location readings, which also use more battery power
_locationManager.desiredAccuracy = kCLLocationAccuracyBest
// The activity type paramater will help the device save some power throughout the user's run
// It will pause location updates when the user does not significantly move
//_locationManager.activityType = .fitness
// Movement threshold for new events
_locationManager.distanceFilter = 5.0
_locationManager.allowsBackgroundLocationUpdates = true
return _locationManager
}()
var myLocation: CLLocation?
lazy var myLocations = [CLLocation]()
lazy var timer = Timer()
var seconds: Int64 = 0
var distance: Int64 = 0
var isStart = false
var kilometers: Int64 = 0
//==================================================
// MARK: - General
//==================================================
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
mapView.showsCompass = true
mapView.showsScale = true
mapView.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
showButton()
showPoints()
}
//==================================================
// MARK: - func
//==================================================
func showStatus(location: CLLocation) {
statusLabel.text = "Altitude: \(Int(location.altitude))m. Speed = \(Int(location.speed*3600/1000))km/h"
}
func stopRoute() {
locationManager.stopUpdatingLocation()
statusLabel.text = "Stop"
isStart = false
showButton()
timer.invalidate()
for overlay in mapView.overlays {
mapView.remove(overlay)
}
}
func eachSecond(timer: Timer) {
seconds += 1
if let myLocation = myLocation {
statusLabel.text = "Altitude: \(Int(myLocation.altitude))m. Speed = \(Int(myLocation.speed*3600/1000))km/h \n"
statusLabel.text = statusLabel.text! + "Time: \(Int(seconds)) s. Distance: \(Int(distance)) m."
}
let km = Int64(distance/1000)
if kilometers != km {
kilometers = km
scheduleNotification()
}
}
func showButton() {
startButton.isEnabled = !isStart
stopButton.isEnabled = isStart
addPointButton.isEnabled = isStart
saveButton.isEnabled = isStart
}
//==================================================
// MARK: - @IBAction
//==================================================
@IBAction func saveButton(_ sender: UIButton) {
if !isStart {
return
}
stopRoute()
if let newRoute = Route(distance: Double(distance), duration: seconds) {
// Create locations array
var savedLocations = [Location]()
for location in self.myLocations {
if let savedLocation = Location(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude, timestamp: location.timestamp) {
savedLocations.append(savedLocation)
}
}
newRoute.locations = NSOrderedSet(array: savedLocations)
CoreDataManager.shared.saveContext()
}
}
@IBAction func stopAction(_ sender: UIButton) {
stopRoute()
}
func addPoint(title: String, subtitle:String, locationCoordinate2D: CLLocationCoordinate2D) {
let title = DateManager.dateAndTimeToString(date: Date())
let subtitle = "addPointAction"
let _anotation = MKPointAnnotation()
_anotation.coordinate = locationCoordinate2D
_anotation.title = title
_anotation.subtitle = subtitle
mapView.addAnnotation(_anotation)
}
@IBAction func addPointAction(_ sender: UIButton) {
if let myLocation = myLocation {
let title = DateManager.dateAndTimeToString(date: Date())
let subtitle = "addPointAction"
let locationCoordinate2D = CLLocationCoordinate2D(latitude: myLocation.coordinate.latitude, longitude: myLocation.coordinate.longitude)
addPoint(title: title, subtitle: subtitle, locationCoordinate2D: locationCoordinate2D)
if Point(latitude: myLocation.coordinate.latitude, longitude: myLocation.coordinate.longitude, title: title, subtitle: subtitle) != nil {
CoreDataManager.shared.saveContext()
}
}
}
@IBAction func startAction(_ sender: UIButton) {
if isStart {
return
}
isStart = true
showButton()
// Reset statistics
seconds = 0
distance = 0
kilometers = 0
myLocations.removeAll(keepingCapacity: false)
// Configure Timer
let updateSelector = #selector(eachSecond(timer:))
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: updateSelector, userInfo: nil, repeats: true)
locationManager.startUpdatingLocation()
}
//==================================================
// MARK: - Notification
//==================================================
func scheduleNotification(){
let content = UNMutableNotificationContent()
content.title = "1000 meters notification demo"
content.subtitle = "Total distance = \(distance)"
content.body = "Good job!"
content.badge = 1
let request = UNNotificationRequest(identifier: "1000meters", content: content, trigger: nil)
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request, withCompletionHandler: nil)
notificationCenter.delegate = self
UIApplication.shared.applicationIconBadgeNumber += 1
}
}
//==================================================
// MARK: - CLLocationManagerDelegate
//==================================================
extension MapViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
for location in locations {
myLocation = location
let howRecent = location.timestamp.timeIntervalSinceNow
// If the devide isn't confident it has a reading within 20 meters of the user's actual location
// It's best to keep it out of your dataset. This check is especially important at the start of the run
// When the device starts narrowing down the general area of the user At this stage it is likely to update with some inaccurate
// data for the first few points.
if abs(howRecent) < 10 && location.horizontalAccuracy < 20 {
// Update distance
if self.myLocations.count > 0 {
// Calculate th distance between the last location and the current location
self.distance += Int64(location.distance(from: self.myLocations.last!))
var coords: [CLLocationCoordinate2D] = []
coords.append(self.myLocations.last!.coordinate)
coords.append(location.coordinate)
// The map always centers on the most recent location
let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 500, 500)
mapView.setRegion(region, animated: true)
// Add little blue polylines to show the user's trail thus far
mapView.add(MKPolyline(coordinates: &coords, count: coords.count))
}
// Save location
self.myLocations.append(location)
}
}
}
func showPoints() {
//removeAnnotations
let annotationsToRemove = mapView.annotations
mapView.removeAnnotations( annotationsToRemove )
//new
let request = NSFetchRequest<NSFetchRequestResult>(entityName: Point.type)
request.predicate = NSPredicate(value: true)
let resultsArray = (try? CoreDataManager.shared.viewContext.fetch(request)) as? [Point]
if (resultsArray?.count)! > 0 {
for point in resultsArray! {
let title = point.title
let subtitle = point.subtitle
let locationCoordinate2D = CLLocationCoordinate2D(latitude: point.latitude, longitude: point.longitude)
addPoint(title: title, subtitle: subtitle, locationCoordinate2D: locationCoordinate2D)
}
}
}
}
//==================================================
// MARK: - MKMapViewDelegate
//==================================================
extension MapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if !overlay.isKind(of: MKPolyline.self) {
return MKOverlayRenderer()
}
let polyline = overlay as! MKPolyline
let renderer = MKPolylineRenderer(polyline: polyline)
renderer.strokeColor = .blue
renderer.lineWidth = 3
return renderer
}
}
//==================================================
// MARK: - UNUserNotificationCenterDelegate
//==================================================
extension MapViewController: UNUserNotificationCenterDelegate{
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print(response.notification.request.content.userInfo)
completionHandler()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
//print("Silently handle no notification")
completionHandler([.alert,.sound])
}
}