-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathCLLocationManager+Promise.swift
More file actions
330 lines (284 loc) · 10.5 KB
/
CLLocationManager+Promise.swift
File metadata and controls
330 lines (284 loc) · 10.5 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
import CoreLocation.CLLocationManager
#if !PMKCocoaPods
import PromiseKit
#endif
/**
To import the `CLLocationManager` category:
use_frameworks!
pod "PromiseKit/CoreLocation"
And then in your sources:
import PromiseKit
*/
extension CLLocationManager {
/// The type of location permission we are asking for
public enum RequestAuthorizationType {
/// Determine the authorization from the application’s plist
case automatic
/// Request always-authorization
case always
/// Request when-in-use-authorization
case whenInUse
}
public enum PMKError: Error {
case notAuthorized
}
/**
Request the current location.
- Note: to obtain a single location use `Promise.lastValue`
- Parameters:
- authorizationType: requestAuthorizationType: We read your Info plist and try to
determine the authorization type we should request automatically. If you
want to force one or the other, change this parameter from its default
value.
- block: A block by which to perform any filtering of the locations that are
returned. In order to only retrieve accurate locations, only return true if the
locations horizontal accuracy < 50
- Returns: A new promise that fulfills with the most recent CLLocation that satisfies
the provided block if it exists. If the block does not exist, simply return the
last location.
- Note: cancelling this promise will cancel the underlying task
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
*/
public class func requestLocation(authorizationType: RequestAuthorizationType = .automatic, satisfying block: ((CLLocation) -> Bool)? = nil) -> Promise<[CLLocation]> {
func std() -> Promise<[CLLocation]> {
return LocationManager(satisfying: block).promise
}
func auth() -> Promise<Void> {
#if os(macOS)
return Promise()
#else
func auth(type: PMKCLAuthorizationType) -> Promise<Void> {
return AuthorizationCatcher(type: type).promise.done(on: nil) {
switch $0 {
case .restricted, .denied:
throw PMKError.notAuthorized
default:
break
}
}
}
switch authorizationType {
case .automatic:
switch Bundle.main.permissionType {
case .always, .both:
return auth(type: .always)
case .whenInUse:
return auth(type: .whenInUse)
}
case .whenInUse:
return auth(type: .whenInUse)
case .always:
return auth(type: .always)
}
#endif
}
switch CLLocationManager.authorizationStatus() {
case .authorizedAlways, .authorizedWhenInUse:
return std()
case .notDetermined:
return auth().then(std)
case .denied, .restricted:
return Promise(error: PMKError.notAuthorized)
}
}
@available(*, deprecated: 5.0, renamed: "requestLocation")
public class func promise(_ requestAuthorizationType: RequestAuthorizationType = .automatic, satisfying block: ((CLLocation) -> Bool)? = nil) -> Promise<[CLLocation]> {
return requestLocation(authorizationType: requestAuthorizationType, satisfying: block)
}
}
private class LocationManager: CLLocationManager, CLLocationManagerDelegate, CancellableTask {
let (promise, seal) = Promise<[CLLocation]>.pending()
let satisfyingBlock: ((CLLocation) -> Bool)?
@objc fileprivate func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let block = satisfyingBlock {
let satisfiedLocations = locations.filter(block)
if !satisfiedLocations.isEmpty {
seal.fulfill(satisfiedLocations)
} else {
#if os(tvOS)
requestLocation()
#endif
}
} else {
seal.fulfill(locations)
}
}
init(satisfying block: ((CLLocation) -> Bool)? = nil) {
satisfyingBlock = block
super.init()
delegate = self
promise.setCancellableTask(self, reject: seal.reject)
#if !os(tvOS)
startUpdatingLocation()
#else
requestLocation()
#endif
_ = self.promise.ensure {
self.stopUpdatingLocation()
}
}
@objc func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
let (domain, code) = { ($0.domain, $0.code) }(error as NSError)
if code == CLError.locationUnknown.rawValue && domain == kCLErrorDomain {
// Apple docs say you should just ignore this error
} else {
seal.reject(error)
}
}
func cancel() {
self.stopUpdatingLocation()
isCancelled = true
}
var isCancelled = false
}
#if !os(macOS)
extension CLLocationManager {
/**
Request CoreLocation authorization from the user
- Note: By default we try to determine the authorization type you want by inspecting your Info.plist
- Note: This method will not perform upgrades from “when-in-use” to “always” unless you specify `.always` for the value of `type`.
- Note: cancelling this promise will cancel the underlying task
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
*/
@available(iOS 8, tvOS 9, watchOS 2, *)
public class func requestAuthorization(type requestedAuthorizationType: RequestAuthorizationType = .automatic) -> Guarantee<CLAuthorizationStatus> {
let currentStatus = CLLocationManager.authorizationStatus()
func std(type: PMKCLAuthorizationType) -> Guarantee<CLAuthorizationStatus> {
if currentStatus == .notDetermined {
return AuthorizationCatcher(type: type).promise
} else {
return .value(currentStatus)
}
}
switch requestedAuthorizationType {
case .always:
func iOS11Check() -> Guarantee<CLAuthorizationStatus> {
switch currentStatus {
case .notDetermined, .authorizedWhenInUse:
return AuthorizationCatcher(type: .always).promise
default:
return .value(currentStatus)
}
}
#if PMKiOS11
// ^^ define PMKiOS11 if you deploy against the iOS 11 SDK
// otherwise the warning you get below cannot be removed
return iOS11Check()
#else
if #available(iOS 11, *) {
return iOS11Check()
} else {
return std(type: .always)
}
#endif
case .whenInUse:
return std(type: .whenInUse)
case .automatic:
if currentStatus == .notDetermined {
switch Bundle.main.permissionType {
case .both, .whenInUse:
return AuthorizationCatcher(type: .whenInUse).promise
case .always:
return AuthorizationCatcher(type: .always).promise
}
} else {
return .value(currentStatus)
}
}
}
}
@available(iOS 8, *)
private class AuthorizationCatcher: CLLocationManager, CLLocationManagerDelegate, CancellableTask {
let (promise, fulfill) = Guarantee<CLAuthorizationStatus>.pending()
var retainCycle: AuthorizationCatcher?
let initialAuthorizationState = CLLocationManager.authorizationStatus()
init(type: PMKCLAuthorizationType) {
super.init()
promise.setCancellableTask(self)
func ask(type: PMKCLAuthorizationType) {
delegate = self
retainCycle = self
switch type {
case .always:
#if os(tvOS)
fallthrough
#else
requestAlwaysAuthorization()
#endif
case .whenInUse:
requestWhenInUseAuthorization()
}
promise.done { _ in
self.retainCycle = nil
}
}
func iOS11Check() {
switch (initialAuthorizationState, type) {
case (.notDetermined, .always), (.authorizedWhenInUse, .always), (.notDetermined, .whenInUse):
ask(type: type)
default:
fulfill(initialAuthorizationState)
}
}
#if PMKiOS11
// ^^ define PMKiOS11 if you deploy against the iOS 11 SDK
// otherwise the warning you get below cannot be removed
iOS11Check()
#else
if #available(iOS 11, *) {
iOS11Check()
} else {
if initialAuthorizationState == .notDetermined {
ask(type: type)
} else {
fulfill(initialAuthorizationState)
}
}
#endif
}
@objc fileprivate func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
// `didChange` is a lie; it fires this immediately with the current status.
if status != initialAuthorizationState {
fulfill(status)
}
}
func cancel() {
self.retainCycle = nil
isCancelled = true
}
var isCancelled = false
}
#endif
private extension Bundle {
enum PermissionType {
case both
case always
case whenInUse
}
var permissionType: PermissionType {
func hasInfoPlistKey(_ key: String) -> Bool {
let value = object(forInfoDictionaryKey: key) as? String ?? ""
return !value.isEmpty
}
if hasInfoPlistKey("NSLocationAlwaysAndWhenInUseUsageDescription") {
return .both
}
if hasInfoPlistKey("NSLocationAlwaysUsageDescription") {
return .always
}
if hasInfoPlistKey("NSLocationWhenInUseUsageDescription") {
return .whenInUse
}
if #available(iOS 11, *) {
NSLog("PromiseKit: warning: `NSLocationAlwaysAndWhenInUseUsageDescription` key not set")
} else {
NSLog("PromiseKit: warning: `NSLocationWhenInUseUsageDescription` key not set")
}
// won't work, but we warned the user above at least
return .whenInUse
}
}
private enum PMKCLAuthorizationType {
case always
case whenInUse
}