在Swift中每30分钟发送一次位置更新 [英] Send location updates every 30 minutes in Swift

查看:114
本文介绍了在Swift中每30分钟发送一次位置更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有位置服务的后台模式,目标是每隔30分钟向服务器发送一个位置(经度和纬度)。现在我在控制台中打印相同的内容。它似乎工作了一段时间,但我想知道如何在这种情况下使用NSTimer。我应该从哪里打电话呢?

I have background mode on for location services and aiming to send out location (latitude and longitude) to the server every 30 minutes. For now I am printing the same in the console. It seems to work for a while but I am wondering how do I work with NSTimer in this case. And from where should I be calling it?

import UIKit
import CoreLocation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {

    var window: UIWindow?
    var locationManager = CLLocationManager()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

        self.locationManager.delegate = self
        self.locationManager.startUpdatingLocation() // I know i should be using signification location option here. this is just for testing now.
    }

    func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
        self.sendBackgroundLocationToServer(newLocation);
    }

    func sendBackgroundLocationToServer(location: CLLocation) {
        var bgTask = UIBackgroundTaskIdentifier()
        bgTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler { () -> Void in
            UIApplication.sharedApplication().endBackgroundTask(bgTask)
        }

        println(location.coordinate.latitude)

        if (bgTask != UIBackgroundTaskInvalid)
        {
            UIApplication.sharedApplication().endBackgroundTask(bgTask);
            bgTask = UIBackgroundTaskInvalid;
        }
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        application.beginBackgroundTaskWithExpirationHandler{}
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        application.beginBackgroundTaskWithExpirationHandler{}
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        application.beginBackgroundTaskWithExpirationHandler{}
    }


}

也许调用 application.beginBackgroundTaskWithExpirationHandler {} 是一个坏主意?我在这里有什么选择?

Maybe calling application.beginBackgroundTaskWithExpirationHandler{} is a bad idea? What options do I go with here?

推荐答案

想法 beginBackgroundTask ... 是开始一个有限长度的任务,这样如果用户离开应用程序,它将继续在后台任务中运行一段短暂的有限时间(3分钟,我相信)。在时间用完之前,你必须调用 endBackgroundTask ,否则应用程序将被立即终止。

The idea of beginBackgroundTask... is to start a finite length task so that if the user leaves the app, it will keep running in the background task for some short, finite period of time (3 minutes, I believe). And before the time runs out, you have to call endBackgroundTask or else the app will be summarily terminated.

所以遗憾的是,后台任务机制并不适合你想要的意图。但是,有一组狭窄的特殊背景模式,用于在一组狭窄的功能(VOIP,音频等)之外继续进行后台操作。有关详细信息,请参阅实施长期运行任务部分BackgroundExecution.htmlrel =nofollow noreferrer>适用于iOS的应用程序编程指南:后台执行

So, sadly, the background task mechanism is not really suited for your desired intent. There are, though, a narrow set of special background modes designed for continued background operation outside a narrow set of functions (VOIP, audio, etc.). For more information, see the Implementing Long-Running Tasks section of the App Programming Guide for iOS: Background Execution.

现在,其中一种后台模式适用于定位服务。因此,如果这是您的应用程序的核心功能,对于正常功能至关重要,那么您可以注册位置后台模式,您的应用程序将继续在后台运行。从那里,您可以监视位置更新,如果已经过了足够的时间,则触发一些进程。但是,如果此背景位置模式不是您应用的基本功能,Apple可能会拒绝您的应用请求其不需要的后台模式。

Now, one of those background modes is for a "location" service. So, if that is a central feature of your app, essential for proper function, then you can register for the location background mode, and your app will continue to run in the background. From there, you can monitor for location updates, and if a sufficient amount of time has elapsed, trigger some process. But if this background location mode is not an essential feature of your app, Apple is likely to reject your app for requesting a background mode that it doesn't need.

顺便提一下,您应该知道启动标准位置服务可能会耗尽设备电池电量。您可以考虑使用电池效率重大变化位置服务。这也具有每次用户移动一些显着距离时自动唤醒您的应用程序的优点(例如以km为单位测量;我相信它是通过移动到不同的手机信号塔触发的)。

By the way, you should be aware that starting standard location services may drain the device battery. You might consider using the battery efficient "significant change" location service. This also has the virtue of automatically waking your app every time the user moves some significant distance (e.g. measured in km; I believe it's triggered by moving to different cell tower).

这篇关于在Swift中每30分钟发送一次位置更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆