当应用程序处于后台模式时,如何将位置连续发送到服务器5小时?

时间:2017-03-03 13:42:37

标签: background swift3 core-location

我正在创建一个应用程序,我必须在Api调用中将位置发送到服务器。它也可以在后台工作。我已经为此实现了代码,但是当我从后台回来时。我目前的工作没有恢复。它只是指向仪表板页面,而不是支持后台页面。

这是我在appdelegate中的代码

func applicationWillEnterForeground(_ application: UIApplication) {

        if !isComingFromTrip {
            locationManager.stopUpdatingLocation()
        }
         locationStarted = false
    }

func applicationDidEnterBackground(_ application: UIApplication) {

    if isComingFromTrip {

    if UIApplication.shared.applicationState == .background {
        print("start backgroun tracking from appdelegate")

        locationManager.startUpdatingLocation()
    }
    //change locationManager status after time
    self.runBackgroundTask(20)
    } else {

        isComingFromTrip = false
    }
    FIRMessaging.messaging().disconnect()
    print("Disconnected from FCM.")
}

func runBackgroundTask(_ time: Int) -> Void {


    if UIApplication.shared.applicationState == .background {
        //create UIBackgroundTaskIdentifier and create tackground task, which starts after time
       backgroundUpdateTask = app.beginBackgroundTask(expirationHandler: {() -> Void in
            self.app.endBackgroundTask(self.backgroundUpdateTask)
            self.backgroundUpdateTask = UIBackgroundTaskInvalid
        })
        DispatchQueue.global(qos: .default).async(execute: {() -> Void in
            var t = Timer.scheduledTimer(timeInterval: TimeInterval(time), target: self, selector: #selector(self.startTrackingBg), userInfo: nil, repeats: false)
            RunLoop.current.add(t, forMode: RunLoopMode.defaultRunLoopMode)
            RunLoop.current.run()
        })
    }
}

func startTrackingBg() {

    //write background time remaining
    print(String(format: "backgroundTimeRemaining: %.0f", UIApplication.shared.backgroundTimeRemaining))
    //set default time
    var time: Int = 60
    //if locationManager is ON
    if locationStarted == true {
        //stop update location
        locationManager.stopUpdatingLocation()
        locationStarted = false
    }
    else {
        //start updating location
        locationManager.startUpdatingLocation()
        locationStarted = true
        //Time how long the application will update your location
        time = 5
    }
    self.runBackgroundTask(time)
}

func StartupdateLocation() {

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = kCLDistanceFilterNone
    locationManager.requestAlwaysAuthorization()
    if #available(iOS 9.0, *) {
        locationManager.allowsBackgroundLocationUpdates = true
    } else {
        // Fallback on earlier versions
    }
    locationManager.pausesLocationUpdatesAutomatically = false
    locationManager.startUpdatingLocation()
}

我已经启用了后台模式,目标 - >功能 - >地点 并为此添加了关键。

0 个答案:

没有答案
相关问题