【问题标题】:Getting the user's location when app is terminated应用程序终止时获取用户的位置
【发布时间】:2017-11-30 08:59:56
【问题描述】:

我目前正在开发一个应用程序,但遇到了问题。 我的应用程序的目的是查看某人何时下班。为此,应用程序应该能够在应用程序打开、后台或终止(被终止)时获取用户的位置,以 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)")
        })

除了在应用程序终止时获取位置之外,一切正常......

提前致谢!

【问题讨论】:

标签: ios swift xcode


【解决方案1】:

经过数小时的搜索和阅读解决方案,我找到了适合我的解决方案。 (注意:我正在研究地理围栏,我需要在用户离开特定区域时通知/调用 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)
    }

希望对你有帮助。

【讨论】:

  • 我希望在应用程序被终止/终止/暂停状态时每 15 分钟更新一次位置。有可能得到吗?
猜你喜欢
  • 2017-05-18
  • 2015-09-25
  • 1970-01-01
  • 2015-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-06
  • 2016-04-07
相关资源
最近更新 更多