-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLocationService.swift
More file actions
125 lines (107 loc) · 2.9 KB
/
LocationService.swift
File metadata and controls
125 lines (107 loc) · 2.9 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
//
// LocationService.swift
// iOSCommon
//
// Created by Ricol Wang on 23/10/19.
//
import CoreLocation
import UIKit
protocol LocationServiceDelegate
{
func locationServicePositionUpdated(lat: Double, lng: Double, accuracy: Double)
func locationServicePositionUpdateFailed(error: Error)
func locationServiceAuthorizationChanged()
func locationServiceNotEnabled()
}
class LocationService: NSObject, CLLocationManagerDelegate
{
static let sharedInstance = LocationService()
var lat: Double = 0
var lng: Double = 0
var accuracy: Double = 0
private var bStartOnce = false
var locationManager = CLLocationManager()
var timer: Timer?
var delegate: LocationServiceDelegate?
override init()
{
super.init()
locationManager.delegate = self
}
func isLocationServiceDetermined() -> Bool
{
return CLLocationManager.authorizationStatus() != .notDetermined
}
func isLocationServiceEnabled() -> Bool
{
let status = CLLocationManager.authorizationStatus()
switch status
{
case .notDetermined, .restricted, .denied:
return false
case .authorizedAlways, .authorizedWhenInUse:
return true
}
}
func requirePermission()
{
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
}
func start()
{
bStartOnce = false
stop()
if isLocationServiceEnabled()
{
locationManager.startUpdatingLocation()
}
else
{
delegate?.locationServiceNotEnabled()
}
}
func startOnce()
{
bStartOnce = true
stop()
if isLocationServiceEnabled()
{
locationManager.startUpdatingLocation()
}
else
{
delegate?.locationServiceNotEnabled()
}
}
func stop()
{
locationManager.stopUpdatingLocation()
}
// MARK: - CLLocationManagerDelegate
func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
if let latestLocation = locations.last
{
lat = latestLocation.coordinate.latitude
lng = latestLocation.coordinate.longitude
accuracy = latestLocation.horizontalAccuracy
delegate?.locationServicePositionUpdated(lat: lat, lng: lng, accuracy: accuracy)
if bStartOnce
{
stop()
}
}
}
func locationManager(_: CLLocationManager, didFailWithError error: Error)
{
lat = 0
lng = 0
accuracy = 0
delegate?.locationServicePositionUpdateFailed(error: error)
}
func locationManager(_: CLLocationManager, didChangeAuthorization _: CLAuthorizationStatus)
{
delegate?.locationServiceAuthorizationChanged()
}
}