【问题标题】:How to get location update in ios using swift even when the app is running in background即使应用程序在后台运行,如何使用 swift 在 ios 中获取位置更新
【发布时间】:2017-02-07 05:06:32
【问题描述】:

我正在开发一个需要定期更新用户位置的应用程序,但是当应用程序暂停或在后台运行时,我无法获取位置更新。我还在功能中启用了后台位置更新。

viewDidLoad 代码:

override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.requestAlwaysAuthorization()
        locationManager.requestWhenInUseAuthorization()
        let user=FIRAuth.auth()?.currentUser?.displayName
        if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse){
            locationManager.requestLocation()
            location=locationManager.location
            locationManager.startUpdatingLocation()
            locationManager.startMonitoringSignificantLocationChanges()
            //updating to database
            ref.child("\(user!)/lat").setValue(location.coordinate.latitude)
            ref.child("\(user!)/long").setValue(location.coordinate.longitude)
            //location=locationManager.location
        }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        location=locations[locations.count-1]
    }

【问题讨论】:

标签: ios iphone swift swift3


【解决方案1】:

启用位置更新 -> 后台模式 -> 功能

我正在使用这种方法在后台获取位置。这个方法写在 AppDelegate 类中

 func getLocation() {
    self.locationManager = CLLocationManager()
    self.locationManager.delegate = self
    if self.locationManager.responds(to: #selector(self.requestAlwaysAuthorization)) {
        self.locationManager.requestAlwaysAuthorization()
    }
    self.locationManager.distanceFilter = kCLDistanceFilterNone
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    if !CLLocationManager.locationServicesEnabled() {
            // location services is disabled, alert user
        var servicesDisabledAlert = UIAlertView(title: "Alert", message: "Location service is disable. Please enable to access your current location.", delegate: nil, cancelButtonTitle: "OK", otherButtonTitles: "")
        servicesDisabledAlert.show()
    }
    else {
        self.locationManager.startUpdatingLocation()
    }
}

【讨论】:

    猜你喜欢
    • 2017-11-16
    • 2019-04-18
    • 1970-01-01
    • 2012-07-05
    • 2015-04-14
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多