简体   繁体   English

用户在后台时更新位置-迅速

[英]Update location when user is in background - swift

I've had an issue for like 3-4 months. 我遇到了3-4个月的问题。 I've tried everything you can ever imagine to get this to work, but I really can't. 我已经尝试了所有您能想到的方法来使它起作用,但是我真的不能。 Now I'm looking for your help to fix this issue. 现在,我正在寻找您的帮助来解决此问题。

I've an application, when you press a start button it should get locations. 我有一个应用程序,当您按下开始按钮时,它应该可以找到位置。 (Works perfectly fine when ur on the application.) But once you leave the application, (not killing the process) and goes to the background. (当您在应用程序上运行时,效果很好。)但是,一旦离开应用程序,(不终止进程)就会转到后台。 The polyline is not drawing like it should. 折线的绘制效果不理想。 It pauses or something. 停顿一下。

I need someone either who can help me here, or create a chatroom with me so we can discuss and I will send the rest of the code. 我需要一个可以在这里为我提供帮助的人,或者与我创建一个聊天室,以便我们进行讨论,然后我将发送其余的代码。

Here is parts of it, which I think is the most important. 这是其中的一部分,我认为这是最重要的。 Inside the viewDidLoad 在viewDidLoad内部

 let app = UIApplication.shared

        NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive(notification:)), name: UIApplication.willResignActiveNotification, object: app)

        NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive(notification:)), name: UIApplication.didBecomeActiveNotification, object: app)

- -

 @objc func applicationWillResignActive(notification: NSNotification)
    {
        start = CFAbsoluteTimeGetCurrent()
        print("Background entered")
        startReceivingSignificantLocationChanges()

    }

    @objc func didBecomeActive(notification: NSNotification)
    {
        let elapsed = CFAbsoluteTimeGetCurrent() - start
        counter = counter + Int(elapsed)
        print("Returned to application")
        locationManager.stopMonitoringSignificantLocationChanges()

    }

< Inside the start button. <在开始按钮内。

//Checking userpermission to allow map and current location
            if (CLLocationManager.locationServicesEnabled())
            {
                locationManager.requestAlwaysAuthorization()
                locationManager.requestWhenInUseAuthorization()

                self.locationManager.allowsBackgroundLocationUpdates = true
                self.locationManager.showsBackgroundLocationIndicator = true

                //Retrieve current position
                if let userLocation = locationManager.location?.coordinate
                {
                    //Zooming in to current position
                    let viewRegion = MKCoordinateRegion(center: userLocation, latitudinalMeters: 200, longitudinalMeters: 200)
                    mapView.setRegion(viewRegion, animated: false)

                    //Creating a start annotation
                    if locations.isEmpty
                    {
                        let annotation = MKPointAnnotation()
                        annotation.title = "Start"
                        annotation.coordinate = userLocation
                        mapView.addAnnotation(annotation)
                    }

                    self.locations.append(userLocation)
                    print(self.locations, "First")

                    //Starts the walk-timer, with interval: 1 second
                    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)

                    //Sending to update
                    update()
                }
            }

< Background worker <背景工作者

func startReceivingSignificantLocationChanges()
    {
        let authorizationStatus = CLLocationManager.authorizationStatus()
        if authorizationStatus != .authorizedAlways
        {
            return
        }

        if !CLLocationManager.significantLocationChangeMonitoringAvailable()
        {
            // The service is not available.
            return
        }
        else
        {
            locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
            locationManager.distanceFilter = 100.0 //100.0 meters
            locationManager.activityType = .fitness
            locationManager.allowsBackgroundLocationUpdates = true
            locationManager.delegate = self
            locationManager.startMonitoringSignificantLocationChanges()
        }
    }

    func locationManager(_ manager: CLLocationManager,  didUpdateLocations
        locations: [CLLocation])
    {
        let lastLocation = locations.last!

        self.locations.append(lastLocation.coordinate)

        print("Locations retrieved from background: ", self.locations)
    }

There is a lot more I've to show you. 我还有很多要给你看的。 But unfortunately it would be way too much... 但是不幸的是,这太多了……

Please enable the Background Modes from the capabilities of the project and enable the 'Location updates'. 请从项目的功能启用后台模式,然后启用“位置更新”。 After enabling this, the only configuration to get the updates in the background(not in killed state) is to set'allowsBackgroundLocationUpdates' to true(which you have done already). 启用此功能后,唯一在后台获取更新(不处于终止状态)的配置是将“ allowsBackgroundLocationUpdates”设置为true(您已经完成)。

Here the significant location changes are only needed when you want to get the location when the application is killed by the user. 在这里,仅当您希望在用户杀死应用程序时获取位置时,才需要进行重大位置更改。 This significant location change will launch the application in background and read the location of the device. 位置的重大更改将在后台启动应用程序并读取设备的位置。 For more information on getting location in the background follow : 有关在后台获取位置的更多信息,请遵循:

https://developer.apple.com/documentation/corelocation/cllocationmanager/1620568-allowsbackgroundlocationupdates https://developer.apple.com/documentation/corelocation/cllocationmanager/1620568-allowsbackgroundlocationupdates

For significant location changes while the application is in killed state, follow below link. 要在应用程序处于终止状态时进行重要的位置更改,请点击以下链接。 This is in objective C but it can be easily done in swift also. 这是在目标C中完成的,但也可以轻松快速地完成。

http://mobileoop.com/getting-location-updates-for-ios-7-and-8-when-the-app-is-killedterminatedsuspended http://mobileoop.com/getting-location-updates-for-ios-7-and-8-when-the-app-is-killedterminatedsuspended

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 IOS - 使用swift运行更新用户位置的后台任务 - IOS - Running background task for update user location using swift 在后台快速更新用户位置 - updating the user location in the background swift 在后台 Swift 中发送用户的位置 - Send Location of User in Background Swift 当应用程序在后台时将用户的位置转发到服务器(Swift/iOS) - Forwarding user's location to server when application is in the background (Swift/iOS) 快速用户位置 - 如果移动则更新 - swift user location - update if move 如何使用Swift 4 iOS在特定时间间隔内更新用户的后台位置? - How to update background location of user within specific time interval using swift 4 iOS? 如何在后台Swift中跟踪用户位置 - How to track user location in the background swift 当用户关闭“ Background App Refresh”时,在后台模式下更新位置不起作用 - Update location on background mode do not work when user turn off “Background App Refresh” 使用Xcode 8和Swift 3在解析中更新用户位置 - Update User Location In Parse Using Xcode 8 and Swift 3 即使应用程序在后台运行,如何使用swift在ios中获取位置更新 - How to get location update in ios using swift even when the app is running in background
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM