[英]Getting the user's location when app is terminated
我目前正在開發應用程序並遇到問題。 我的應用程序的目的是看看有人離開工作。 為了使其在100%的時間內工作,應用程序應該能夠在應用程序打開時,在后台或終止(被殺死)時獲取用戶的位置。 我的理解是你必須使用重要的位置更改功能。 但是,它沒有按預期工作。
AppDelegate中:
//handle location changes when app is terminated and waken up by the OS
if launchOptions?[UIApplicationLaunchOptionsKey.location] != nil {
print("Restarted app due to a location update")
request = Locator.subscribeSignificantLocations(onUpdate: { newLoc in
let db: FirebaseDB = FirebaseDB.shared
db.postCoordinates(coordinates: CLLocation(latitude: 9.99, longitude: 9.99))
print("new loc found -> \(newLoc)")
}, onFail: {(err, lastLoc) in
print("failed to get loc, -> \(err)")
})
//send new post to DB
}
//subscribeSignificantLocations -> power efficient
request = Locator.subscribeSignificantLocations(onUpdate: { newLoc in
print("new loc found -> \(newLoc)")
}, onFail: {(err, lastLoc) in
print("failed to get new loc, -> \(err)")
})
一切正常,除了在應用程序終止時獲取位置...
提前致謝!
經過幾個小時的搜索和閱讀解決方案,我找到了一個有效的解決方案。 ( 注意:我正在進行地理圍欄,我需要在用戶離開某個區域時通知/調用API )
第一個也是最重要的一步是由用戶進行“始終”授權以進行位置訪問。
其次,即使在應用程序終止后,我們也需要使用startMonitoringSignificantLocationChanges()
進行位置更新。
locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
locationManager.allowsBackgroundLocationUpdates = true
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges() //THIS IS WHERE THE MAGIC HAPPENS
以下是獲取位置更新的本地通知的代碼。
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
var window: UIWindow?
let locationManager = CLLocationManager()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
locationManager.allowsBackgroundLocationUpdates = true
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
application.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
UIApplication.shared.cancelAllLocalNotifications()
return true
}
func alertUserOnLeaving(region:CLRegion){
if UIApplication.shared.applicationState == .active {
let alert = UIAlertController(title: "Alert Title", message: "Alert Message", style = .Alert
window?.rootViewController?.present(alert, animated: true, completion: nil)
}
else{
let notification = UILocalNotification()
notification.alertBody = "You forgot to checkout"
notification.soundName = "Default"
UIApplication.shared.presentLocalNotificationNow(notification)
}
}
func alertUserOnArrival(region:CLRegion){
if UIApplication.shared.applicationState == .active {
let alert = UIAlertController(title: "Alert Title", message: "Alert Message", style = .Alert
window?.rootViewController?.present(alert, animated: true, completion: nil)
}
else{
let notification = UILocalNotification()
notification.alertBody = "Welcome Please checkin"
notification.soundName = "Default"
UIApplication.shared.presentLocalNotificationNow(notification)
}
}
func setUpGeofenceForJob() {
let geofenceRegionCenter = CLLocationCoordinate2DMake(-33.7513580322265, 151.242416381836)
let geofenceRegion = CLCircularRegion(center: geofenceRegionCenter, radius: 100, identifier: "GeoFence")
geofenceRegion.notifyOnExit = true
geofenceRegion.notifyOnEntry = true
self.locationManager.startMonitoring(for: geofenceRegion)
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if (status == CLAuthorizationStatus.authorizedAlways) {
self.setUpGeofenceForJob()
}
}
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
alertUserOnArrival(region: region)
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
alertUserOnLeaving(region: region)
}
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.