如何在我的 iOS 应用程序中每 n 分钟获取一次后台位置更新?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6347503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get a background location update every n minutes in my iOS application?
提问by wjans
I'm looking for a way to get a background location update every n minutes in my iOS application. I'm using iOS 4.3 and the solution should work for non-jailbroken iPhones.
我正在寻找一种在我的 iOS 应用程序中每 n 分钟更新一次后台位置的方法。我使用的是 iOS 4.3,该解决方案应该适用于未越狱的 iPhone。
I tried / considered following options:
我尝试/考虑过以下选项:
CLLocationManager startUpdatingLocation/startMonitoringSignificantLocationChanges
: This works in the background as expected, based on the configured properties, but it seems not possible to force it to update the location every n minutesNSTimer
: Does work when the app is running in the foreground but doesn't seem to be designed for background tasks- Local notifications: Local notifications can be scheduled every n minutes, but it's not possible to execute some code to get the current location (without the user having to launch the app via the notification). This approach also doesn't seem to be a clean approach as this is not what notifications should be used for.
UIApplication:beginBackgroundTaskWithExpirationHandler
: As far as I understand, this should be used to finish some work in the background (also limited in time) when an app is moved to the background rather than implementing "long-running" background processes.
CLLocationManager startUpdatingLocation/startMonitoringSignificantLocationChanges
:这在后台按预期工作,基于配置的属性,但似乎不可能强制它每 n 分钟更新一次位置NSTimer
:当应用程序在前台运行时有效,但似乎不是为后台任务设计的- 本地通知:本地通知可以每 n 分钟安排一次,但无法执行某些代码来获取当前位置(用户无需通过通知启动应用程序)。这种方法似乎也不是一种干净的方法,因为这不是通知的用途。
UIApplication:beginBackgroundTaskWithExpirationHandler
:据我所知,当应用程序移至后台时,这应该用于在后台完成一些工作(也有时间限制),而不是实现“长时间运行”的后台进程。
How can I implement these regular background location updates?
如何实现这些定期的后台位置更新?
采纳答案by wjans
I found a solution to implement this with the help of the Apple Developer Forums:
我在 Apple Developer Forums 的帮助下找到了一个解决方案来实现这个:
- Specify
location background mode
- Create an
NSTimer
in the background withUIApplication:beginBackgroundTaskWithExpirationHandler:
- When
n
is smallerthanUIApplication:backgroundTimeRemaining
it will work just fine. Whenn
is larger, thelocation manager
should be enabled (and disabled) again before there is no time remaining to avoid the background task being killed.
- 指定
location background mode
NSTimer
在后台创建一个UIApplication:beginBackgroundTaskWithExpirationHandler:
- 如果
n
是小的比UIApplication:backgroundTimeRemaining
它会工作得很好。如果n
是较大的,则location manager
应该启用(和残疾人)再之前还有剩余,避免后台任务被杀死没有时间。
This works because location is one of the three allowed types of background execution.
这是有效的,因为 location 是三种允许的后台执行类型之一。
Note: I lost some time by testing this in the simulator where it doesn't work. However, it works fine on my phone.
注意:我通过在模拟器中测试它而失去了一些时间,但它不起作用。但是,它在我的手机上运行良好。
回答by Leszek Szary
On iOS 8/9/10to make background location update every 5 minutes do the following:
在iOS 8/9/10上每 5 分钟更新一次后台位置,请执行以下操作:
Go to Project -> Capabilities -> Background Modes -> select Location updates
Go to Project -> Info -> add a key NSLocationAlwaysUsageDescription with empty value (or optionally any text)
To make location working when your app is in the background and send coordinates to web service or do anything with them every 5 minutes implement it like in the code below.
转到项目 -> 功能 -> 背景模式 -> 选择位置更新
转到 Project -> Info -> 添加一个键 NSLocationAlwaysUsageDescription 与空值(或可选的任何文本)
要在您的应用程序在后台运行并将坐标发送到 Web 服务或每 5 分钟对它们执行任何操作时使定位工作,请像下面的代码一样实现它。
I'm not using any background tasks or timers. I've tested this code with my device with iOS 8.1 which was lying on my desk for few hours with my app running in the background. Device was locked and the code was running properly all the time.
我没有使用任何后台任务或计时器。我已经在我的 iOS 8.1 设备上测试了这段代码,它在我的桌子上躺了几个小时,我的应用程序在后台运行。设备被锁定,代码一直在正常运行。
@interface LocationManager () <CLLocationManagerDelegate>
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) NSDate *lastTimestamp;
@end
@implementation LocationManager
+ (instancetype)sharedInstance
{
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
LocationManager *instance = sharedInstance;
instance.locationManager = [CLLocationManager new];
instance.locationManager.delegate = instance;
instance.locationManager.desiredAccuracy = kCLLocationAccuracyBest; // you can use kCLLocationAccuracyHundredMeters to get better battery life
instance.locationManager.pausesLocationUpdatesAutomatically = NO; // this is important
});
return sharedInstance;
}
- (void)startUpdatingLocation
{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
if (status == kCLAuthorizationStatusDenied)
{
NSLog(@"Location services are disabled in settings.");
}
else
{
// for iOS 8
if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
{
[self.locationManager requestAlwaysAuthorization];
}
// for iOS 9
if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)])
{
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
}
[self.locationManager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *mostRecentLocation = locations.lastObject;
NSLog(@"Current location: %@ %@", @(mostRecentLocation.coordinate.latitude), @(mostRecentLocation.coordinate.longitude));
NSDate *now = [NSDate date];
NSTimeInterval interval = self.lastTimestamp ? [now timeIntervalSinceDate:self.lastTimestamp] : 0;
if (!self.lastTimestamp || interval >= 5 * 60)
{
self.lastTimestamp = now;
NSLog(@"Sending current location to web service.");
}
}
@end
回答by Bushra Shahid
I did this in an application I'm developing. The timers don't work when the app is in the background but the app is constantly receiving the location updates. I read somewhere in the documentation (i can't seem to find it now, i'll post an update when i do) that a method can be called only on an active run loop when the app is in the background. The app delegate has an active run loop even in the bg so you dont need to create your own to make this work. [Im not sure if this is the correct explanation but thats how I understood from what i read]
我在我正在开发的应用程序中做到了这一点。当应用程序处于后台但应用程序不断接收位置更新时,计时器不起作用。我在文档中的某处读到(我现在似乎找不到它,我会在我做的时候发布更新),当应用程序处于后台时,只能在活动的运行循环上调用方法。即使在 bg 中,应用程序委托也有一个活动的运行循环,因此您不需要创建自己的运行循环来完成这项工作。[我不确定这是否是正确的解释,但这就是我从我阅读的内容中理解的]
First of all, add the location
object for the key UIBackgroundModes
in your app's info.plist. Now, what you need to do is start the location updates anywhere in your app:
首先,在应用程序的 info.plist 中添加location
键的对象UIBackgroundModes
。现在,您需要做的是在您的应用程序中的任何位置开始位置更新:
CLLocationManager locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;//or whatever class you have for managing location
[locationManager startUpdatingLocation];
Next, write a method to handle the location updates,
say -(void)didUpdateToLocation:(CLLocation*)location
, in the app delegate. Then implement the method locationManager:didUpdateLocation:fromLocation
of CLLocationManagerDelegate
in the class in which you started the location manager (since we set the location manager delegate to 'self'). Inside this method you need to check if the time interval after which you have to handle the location updates has elapsed. You can do this by saving the current time every time. If that time has elapsed, call the method UpdateLocation from your app delegate:
接下来,-(void)didUpdateToLocation:(CLLocation*)location
在应用程序委托中编写一个方法来处理位置更新。然后实现方法locationManager:didUpdateLocation:fromLocation
的CLLocationManagerDelegate
在其中您开始位置管理类(因为我们设置的位置经理授人以“自我”)。在此方法中,您需要检查您必须处理位置更新的时间间隔是否已经过去。您可以通过每次保存当前时间来做到这一点。如果该时间已过,请从您的应用程序委托调用方法 UpdateLocation:
NSDate *newLocationTimestamp = newLocation.timestamp;
NSDate *lastLocationUpdateTiemstamp;
int locationUpdateInterval = 300;//5 mins
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if (userDefaults) {
lastLocationUpdateTiemstamp = [userDefaults objectForKey:kLastLocationUpdateTimestamp];
if (!([newLocationTimestamp timeIntervalSinceDate:lastLocationUpdateTiemstamp] < locationUpdateInterval)) {
//NSLog(@"New Location: %@", newLocation);
[(AppDelegate*)[UIApplication sharedApplication].delegate didUpdateToLocation:newLocation];
[userDefaults setObject:newLocationTimestamp forKey:kLastLocationUpdateTimestamp];
}
}
}
This will call your method every 5 mins even when your app is in background.
Imp: This implementation drains the battery, if your location data's accuracy is not critical you should use [locationManager startMonitoringSignificantLocationChanges]
即使您的应用程序在后台,这也会每 5 分钟调用一次您的方法。Imp:此实现会耗尽电池电量,如果您的位置数据的准确性不重要,则应使用[locationManager startMonitoringSignificantLocationChanges]
Before adding this to your app, please read the Location Awareness Programming Guide
在将此添加到您的应用程序之前,请阅读位置感知编程指南
回答by Alejandro Luengo
Now that iOS6 is out the best way to have a forever running location services is...
现在,iOS6 是拥有永久运行位置服务的最佳方式是......
- (void)applicationWillResignActive:(UIApplication *)application
{
/*
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.
*/
NSLog(@"to background");
app.isInBackground = TRUE;
UIApplication *app = [UIApplication sharedApplication];
// Request permission to run in the background. Provide an
// expiration handler in case the task runs long.
NSAssert(bgTask == UIBackgroundTaskInvalid, nil);
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
// Synchronize the cleanup call on the main thread in case
// the task actually finishes at around the same time.
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task.
locationManager.distanceFilter = 100;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[locationManager startMonitoringSignificantLocationChanges];
[locationManager startUpdatingLocation];
NSLog(@"App staus: applicationDidEnterBackground");
// Synchronize the cleanup call on the main thread in case
// the expiration handler is fired at the same time.
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
});
NSLog(@"backgroundTimeRemaining: %.0f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
}
Just tested it like that:
只是这样测试它:
I started the app, go background and move in the car by some minutes. Then I go home for 1 hour and start moving again (without opening again the app). Locations started again. Then stopped for two hours and started again. Everything ok again...
我启动了应用程序,进入后台并在几分钟内进入车内。然后,我回家1小时,再次开始移动(没有再次打开该应用)。位置又开始了。然后停了两个小时又开始了。一切又好了...
DO NOT FORGET USING the new location services in iOS6
不要忘记在 iOS6 中使用新的位置服务
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *loc = [locations lastObject];
// Lat/Lon
float latitudeMe = loc.coordinate.latitude;
float longitudeMe = loc.coordinate.longitude;
}
回答by HelmiB
To someone else having nightmare figure out this one. I have a simple solution.
给做噩梦的其他人找出这个。我有一个简单的解决方案。
- look this example from raywenderlich.com-> have sample code, this works perfectly, but unfortunately no timer during background location. this will run indefinitely.
Add timer by using :
-(void)applicationDidEnterBackground { [self.locationManager stopUpdatingLocation]; UIApplication* app = [UIApplication sharedApplication]; bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; self.timer = [NSTimer scheduledTimerWithTimeInterval:intervalBackgroundUpdate target:self.locationManager selector:@selector(startUpdatingLocation) userInfo:nil repeats:YES]; }
Just don't forget to add "App registers for location updates" in info.plist.
- 看看来自raywenderlich.com 的这个例子-> 有示例代码,这很完美,但不幸的是在后台定位期间没有计时器。这将无限期运行。
使用以下方法添加计时器:
-(void)applicationDidEnterBackground { [self.locationManager stopUpdatingLocation]; UIApplication* app = [UIApplication sharedApplication]; bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; self.timer = [NSTimer scheduledTimerWithTimeInterval:intervalBackgroundUpdate target:self.locationManager selector:@selector(startUpdatingLocation) userInfo:nil repeats:YES]; }
只是不要忘记在 info.plist 中添加“应用程序注册位置更新”。
回答by hmitkov
Here is what I use:
这是我使用的:
import Foundation
import CoreLocation
import UIKit
class BackgroundLocationManager :NSObject, CLLocationManagerDelegate {
static let instance = BackgroundLocationManager()
static let BACKGROUND_TIMER = 150.0 // restart location manager every 150 seconds
static let UPDATE_SERVER_INTERVAL = 60 * 60 // 1 hour - once every 1 hour send location to server
let locationManager = CLLocationManager()
var timer:NSTimer?
var currentBgTaskId : UIBackgroundTaskIdentifier?
var lastLocationDate : NSDate = NSDate()
private override init(){
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
locationManager.activityType = .Other;
locationManager.distanceFilter = kCLDistanceFilterNone;
if #available(iOS 9, *){
locationManager.allowsBackgroundLocationUpdates = true
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.applicationEnterBackground), name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
func applicationEnterBackground(){
FileLogger.log("applicationEnterBackground")
start()
}
func start(){
if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedAlways){
if #available(iOS 9, *){
locationManager.requestLocation()
} else {
locationManager.startUpdatingLocation()
}
} else {
locationManager.requestAlwaysAuthorization()
}
}
func restart (){
timer?.invalidate()
timer = nil
start()
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case CLAuthorizationStatus.Restricted:
//log("Restricted Access to location")
case CLAuthorizationStatus.Denied:
//log("User denied access to location")
case CLAuthorizationStatus.NotDetermined:
//log("Status not determined")
default:
//log("startUpdatintLocation")
if #available(iOS 9, *){
locationManager.requestLocation()
} else {
locationManager.startUpdatingLocation()
}
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if(timer==nil){
// The locations array is sorted in chronologically ascending order, so the
// last element is the most recent
guard let location = locations.last else {return}
beginNewBackgroundTask()
locationManager.stopUpdatingLocation()
let now = NSDate()
if(isItTime(now)){
//TODO: Every n minutes do whatever you want with the new location. Like for example sendLocationToServer(location, now:now)
}
}
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
CrashReporter.recordError(error)
beginNewBackgroundTask()
locationManager.stopUpdatingLocation()
}
func isItTime(now:NSDate) -> Bool {
let timePast = now.timeIntervalSinceDate(lastLocationDate)
let intervalExceeded = Int(timePast) > BackgroundLocationManager.UPDATE_SERVER_INTERVAL
return intervalExceeded;
}
func sendLocationToServer(location:CLLocation, now:NSDate){
//TODO
}
func beginNewBackgroundTask(){
var previousTaskId = currentBgTaskId;
currentBgTaskId = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
FileLogger.log("task expired: ")
})
if let taskId = previousTaskId{
UIApplication.sharedApplication().endBackgroundTask(taskId)
previousTaskId = UIBackgroundTaskInvalid
}
timer = NSTimer.scheduledTimerWithTimeInterval(BackgroundLocationManager.BACKGROUND_TIMER, target: self, selector: #selector(self.restart),userInfo: nil, repeats: false)
}
}
I start the tracking in AppDelegate like that:
我像这样在 AppDelegate 中开始跟踪:
BackgroundLocationManager.instance.start()
回答by Chazbot
Unfortunately, all of your assumptions seem correct, and I don't think there's a way to do this. In order to save battery life, the iPhone's location services are based on movement. If the phone sits in one spot, it's invisible to location services.
不幸的是,您的所有假设似乎都是正确的,我认为没有办法做到这一点。为了节省电池寿命,iPhone 的定位服务是基于移动的。如果手机放在一个地方,定位服务就看不到它。
The CLLocationManager
will only call locationManager:didUpdateToLocation:fromLocation:
when the phone receives a location update, which only happens if one of the three location services (cell tower, gps, wifi) perceives a change.
该CLLocationManager
会只调用locationManager:didUpdateToLocation:fromLocation:
当手机接收到一个位置更新,其中只有三个位置服务中的一个(手机信号塔,GPS,WIFI)感知的变化发生。
A few other things that might help inform further solutions:
其他一些可能有助于提供进一步解决方案的信息:
Starting & Stopping the services causes the
didUpdateToLocation
delegate method to be called, but thenewLocation
might have an old timestamp.When running in the background, be aware that it may be difficult to get "full" LocationServices support approved by Apple. From what I've seen, they've specifically designed
startMonitoringSignificantLocationChanges
as a low power alternative for apps that need background location support, and strongly encourage developers to use this unless the app absolutely needs it.
启动和停止服务会导致
didUpdateToLocation
调用委托方法,但newLocation
可能具有旧时间戳。在后台运行时,请注意可能很难获得 Apple 批准的“完整”LocationServices 支持。据我所知,他们专门
startMonitoringSignificantLocationChanges
为需要后台位置支持的应用程序设计了低功耗替代方案,并强烈鼓励开发人员使用它,除非应用程序绝对需要它。
Good Luck!
祝你好运!
UPDATE: These thoughts may be out of date by now. Looks as though people are having success with @wjans answer, above.
更新:这些想法现在可能已经过时了。看起来好像人的游戏@wjans答案的成功,上面。
回答by samthui7
I did write an app using Location services, app must send location every 10s. And it worked very well.
我确实使用位置服务编写了一个应用程序,应用程序必须每 10 秒发送一次位置。而且效果很好。
Just use the "allowDeferredLocationUpdatesUntilTraveled:timeout" method, following Apple's doc.
只需按照 Apple 的文档使用“ allowDeferredLocationUpdatesUntilTraveled:timeout”方法。
What I did are:
我所做的是:
Required:Register background mode for update Location.
要求:为更新位置注册后台模式。
1.Create LocationManger
and startUpdatingLocation
, with accuracy
and filteredDistance
as whatever you want:
1.随心所欲地创建LocationManger
and startUpdatingLocation
, with accuracy
and filteredDistance
:
-(void) initLocationManager
{
// Create the manager object
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
_locationManager.delegate = self;
// This is the most important property to set for the manager. It ultimately determines how the manager will
// attempt to acquire location and thus, the amount of power that will be consumed.
_locationManager.desiredAccuracy = 45;
_locationManager.distanceFilter = 100;
// Once configured, the location manager must be "started".
[_locationManager startUpdatingLocation];
}
2.To keep app run forever using allowDeferredLocationUpdatesUntilTraveled:timeout
method in background, you must restart updatingLocation
with new parameter when app moves to background, like this:
2.为了让应用程序allowDeferredLocationUpdatesUntilTraveled:timeout
在后台使用方法永远运行,updatingLocation
当应用程序移至后台时,您必须使用新参数重新启动,如下所示:
- (void)applicationWillResignActive:(UIApplication *)application {
_isBackgroundMode = YES;
[_locationManager stopUpdatingLocation];
[_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[_locationManager setDistanceFilter:kCLDistanceFilterNone];
_locationManager.pausesLocationUpdatesAutomatically = NO;
_locationManager.activityType = CLActivityTypeAutomotiveNavigation;
[_locationManager startUpdatingLocation];
}
3.App gets updatedLocations as normal with locationManager:didUpdateLocations:
callback:
3.应用程序通过locationManager:didUpdateLocations:
回调正常获取updatedLocations :
-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
// store data
CLLocation *newLocation = [locations lastObject];
self.userLocation = newLocation;
//tell the centralManager that you want to deferred this updatedLocation
if (_isBackgroundMode && !_deferringUpdates)
{
_deferringUpdates = YES;
[self.locationManager allowDeferredLocationUpdatesUntilTraveled:CLLocationDistanceMax timeout:10];
}
}
4.But you should handle the data in then locationManager:didFinishDeferredUpdatesWithError:
callback for your purpose
4.但是你应该locationManager:didFinishDeferredUpdatesWithError:
根据你的目的处理 then回调中的数据
- (void) locationManager:(CLLocationManager *)manager didFinishDeferredUpdatesWithError:(NSError *)error {
_deferringUpdates = NO;
//do something
}
5.NOTE:I think we should reset parameters of LocationManager
each time app switches between background/forground mode.
5.注意:我认为我们应该在LocationManager
每次应用程序在后台/前台模式之间切换时重置参数。
回答by Nilesh
if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
}
This is needed for background location tracking since iOS 9.
因为iOS的9这需要后台位置跟踪。
回答by nickfox
I used xs2bush's method of getting an interval (using timeIntervalSinceDate
) and expanded on it a little bit. I wanted to make sure that I was getting the required accuracy that I needed and also that I was not running down the battery by keeping the gps radio on more than necessary.
我使用了 xs2bush 的获取间隔的方法(使用timeIntervalSinceDate
)并对其进行了一些扩展。我想确保我得到所要求的精度,我需要而且,我没有通过保持GPS无线电上超过必要的电池电量耗尽。
I keep location running continuously with the following settings:
我使用以下设置保持位置连续运行:
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
locationManager.distanceFilter = 5;
this is a relatively low drain on the battery. When I'm ready to get my next periodic location reading, I first check to see if the location is within my desired accuracy, if it is, I then use the location. If it's not, then I increase the accuracy with this:
这是对电池的相对较低的消耗。当我准备好我的下一个周期性位置读数,我第一次检查,看看是否位置是我需要的精度范围内,如果是这样,然后我使用的位置。如果不是,那么我会通过以下方法提高准确性:
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
locationManager.distanceFilter = 0;
get my location and then once I have the location I turn the accuracy back down again to minimize the drain on the battery. I have written a full working sample of this and also I have written the source for the server side code to collect the location data, store it to a database and allow users to view gps data in real time or retrieve and view previously stored routes. I have clients for iOS, android, windows phone and java me. All clients are natively written and they all work properly in the background. The project is MIT licensed.
获取我的位置,然后一旦我找到了位置,我就会再次降低精度以最大程度地减少电池消耗。我已经编写了一个完整的工作示例,并且还编写了服务器端代码的源代码来收集位置数据,将其存储到数据库中,并允许用户实时查看 gps 数据或检索和查看以前存储的路线。我有 iOS、android、windows 手机和 java me 的客户端。所有客户端都是本地编写的,并且它们都在后台正常工作。该项目已获得 MIT 许可。
The iOS project is targeted for iOS 6 using a base SDK of iOS 7. You can get the code here.
iOS 项目针对使用 iOS 7 基础 SDK 的 iOS 6。您可以在此处获取代码。
Please file an issue on github if you see any problems with it. Thanks.
如果您发现任何问题,请在 github 上提出问题。谢谢。