ios - 即使应用程序在后台运行,如何使用 swift 在 ios 中获取位置更新

标签 ios iphone swift swift3

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

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]
    }

最佳答案

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

我正在使用这种方法在后台获取位置。这个方法写在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()
    }
}

关于ios - 即使应用程序在后台运行,如何使用 swift 在 ios 中获取位置更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42082147/

相关文章:

iphone - 如何查看被释放后正在接收消息的对象

ios - 将结构数组发布到 firebase swift

iOS ,NSDocumentDirectory 获取 nsurl 或路径文件

ios - 如何使用代码中的标识符触发一系列(自动)segues

iphone - iOS - 以编程方式在 TableRow 的右侧添加 ToggleSwitch

ios - 如何以最佳方式添加 ScrollView 以优化为 4 英寸兼容 3.5 英寸设计的屏幕尺寸?

ios - Xcode 6 Interface Builder在 View 中间居中多个标签

ios - textFieldDidBeginEditing : not getting called

ios - CGRect 大小和点返回 0

iPhone加载更多tableViewCell