forked from rn-bridge/react-native-geofencing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGeofencing.swift
262 lines (218 loc) · 9.75 KB
/
Geofencing.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
import CoreLocation
import React
@objc(Geofencing)
class Geofencing: RCTEventEmitter, CLLocationManagerDelegate {
private var locationManager: CLLocationManager
private var hasListeners = false
private var allowWhileUsing = false
private var allowAlways = false
private var authorizationSuccessCallback: RCTResponseSenderBlock?
override init() {
locationManager = CLLocationManager()
super.init()
locationManager.delegate = self
}
override static func requiresMainQueueSetup() -> Bool {
return true
}
@objc(getLocationAuthorizationStatus:withReject:)
func getLocationAuthorizationStatus(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
resolve(getLocationAuthorizationStatus())
}
func geocode(latitude: Double, longitude: Double, callback: @escaping (CLPlacemark?, Error?) -> ()) {
CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude)) { callback($0?.first, $1)
}
}
@objc(getCurrentLocation: withReject:)
func getCurrentLocation(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
if !isLocationAuthorized() {
reject("Permission", "Location permission not given", NSError(domain: "getCurrentLocation", code: 200))
return
}
let location = locationManager.location
let response: NSMutableDictionary = [:]
let latitude = location?.coordinate.latitude ?? 0
let longitude = location?.coordinate.longitude ?? 0
response["latitude"] = location?.coordinate.latitude
response["longitude"] = location?.coordinate.longitude
response["altitude"] = location?.altitude
geocode(latitude: latitude, longitude: longitude) { placemark, error in
guard let placemark = placemark, error == nil else {
resolve(response)
return
}
response["name"] = placemark.name
response["city"] = placemark.locality
response["state"] = placemark.administrativeArea
response["postalCode"] = placemark.postalCode
response["country"] = placemark.country
response["isoCountryCode"] = placemark.isoCountryCode
response["timeZone"] = placemark.timeZone?.identifier
resolve(response)
}
}
@objc(requestLocation: withSuccessCallback:)
func requestLocation(params: NSDictionary, successCallback: @escaping RCTResponseSenderBlock) {
guard let allowWhileUsing = params["allowWhileUsing"] as? Bool,
let allowAlways = params["allowAlways"] as? Bool else {
return
}
if allowWhileUsing && isLocationAuthorized() {
successCallback([["success": true, "location": getLocationAuthorizationStatus()]])
return
}
if allowAlways && CLLocationManager.authorizationStatus() == .authorizedAlways {
successCallback([["success": true, "location": getLocationAuthorizationStatus()]])
return
}
self.allowWhileUsing = allowWhileUsing
self.allowAlways = allowAlways
authorizationSuccessCallback = successCallback
if allowAlways && CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
requestAlwaysAuthorization()
} else {
locationManager.requestWhenInUseAuthorization()
}
}
@objc(getRegisteredGeofences:withReject:)
func getRegisteredGeofences(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
if !isLocationAuthorized() {
reject("Permission", "Location permission not given", NSError(domain: "getRegisteredGeofences", code: 200))
return
}
let regions = locationManager.monitoredRegions
let geofences: [String] = regions.map { region in region.identifier }
resolve(geofences)
}
@objc(addGeofence:withResolve:withReject:)
func addGeofence(params: NSDictionary, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
if !isLocationAuthorized() {
reject("Permission", "Location permission not given", NSError(domain: "addGeofence", code: 200))
return
}
guard let id = params["id"] as? String,
let latitude = params["latitude"] as? Double,
let longitude = params["longitude"] as? Double,
let radius = params["radius"] as? Double else {
reject("Invalid", "Invalid input", NSError(domain: "addGeofence", code: 200))
return
}
let center = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let region = CLCircularRegion(center: center, radius: radius, identifier: id)
locationManager.startMonitoring(for: region)
resolve(["success": true, "id": id])
}
@objc(removeGeofence:withResolve:withReject:)
func removeGeofence(id: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
if removeGeofence(id) {
resolve(["success": true, "id": id])
} else {
resolve(["success": false, "error": "Geofence is not registered with the provided id"])
}
}
@objc(removeAllGeofence:withReject:)
func removeAllGeofence(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
do {
try removeAll()
resolve(["success": true])
} catch let error {
resolve(["success": false, "error": error.localizedDescription])
}
}
private func removeAll() throws {
for region in locationManager.monitoredRegions {
locationManager.stopMonitoring(for: region)
}
}
private func removeGeofence(_ id: String) -> Bool {
for region in locationManager.monitoredRegions {
if region.identifier == id {
locationManager.stopMonitoring(for: region)
return true
}
}
return false
}
override func supportedEvents() -> [String]! {
return ["onEnter", "onExit"]
}
override func startObserving() {
hasListeners = true
}
override func stopObserving() {
hasListeners = false
}
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
if hasListeners {
sendEvent(withName: "onEnter", body: [region.identifier])
} else {
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
// wait for the react native to add listener
self.sendEvent(withName: "onEnter", body: [region.identifier])
}
}
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
if hasListeners {
sendEvent(withName: "onExit", body: [region.identifier])
} else {
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
// wait for the react native to add listener
self.sendEvent(withName: "onExit", body: [region.identifier])
}
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedAlways {
locationManager.allowsBackgroundLocationUpdates = true
authorizationSuccessCallback?([["success": true, "location": getLocationAuthorizationStatus()]])
authorizationSuccessCallback = nil
} else if status == .authorizedWhenInUse {
if self.allowAlways {
requestAlwaysAuthorization()
} else {
authorizationSuccessCallback?([["success": true, "location": getLocationAuthorizationStatus()]])
authorizationSuccessCallback = nil
}
} else {
authorizationSuccessCallback?([["success": false, "location": getLocationAuthorizationStatus()]])
authorizationSuccessCallback = nil
}
}
private func isLocationAuthorized() -> Bool {
return CLLocationManager.authorizationStatus() == .authorizedWhenInUse || CLLocationManager.authorizationStatus() == .authorizedAlways
}
private func getLocationAuthorizationStatus() -> String {
let authorizationStatus = CLLocationManager.authorizationStatus()
var message: String
switch authorizationStatus {
case .authorizedAlways:
message = "Always"
case .authorizedWhenInUse:
message = "WhenInUse"
case .notDetermined:
message = "NotDetermined"
case .restricted:
message = "Restricted"
case .denied:
message = "Denied"
default:
message = "Unknown"
}
return message
}
private func requestAlwaysAuthorization() {
if isBackgroundLocationUpdatesEnabled() {
locationManager.requestAlwaysAuthorization()
} else {
authorizationSuccessCallback?([["success": false, "location": getLocationAuthorizationStatus(), "reason": "Location updates background mode is not enabled"]])
authorizationSuccessCallback = nil
}
}
private func isBackgroundLocationUpdatesEnabled() -> Bool {
if let backgroundModes = Bundle.main.object(forInfoDictionaryKey: "UIBackgroundModes") as? [String] {
return backgroundModes.contains("location")
}
return false
}
}