3 回答

TA貢獻1906條經(jīng)驗 獲得超10個贊
指定 location background mode
創(chuàng)建一個 NSTimer
在背景中 UIApplication:beginBackgroundTaskWithExpirationHandler:
什么時候 n
是 較小
比 UIApplication:backgroundTimeRemaining
一切都會好起來的。什么時候 n
是 更大
, location manager
在沒有時間避免后臺任務被殺死之前,應該再次啟用(并禁用)。
這是因為位置是允許的三種背景執(zhí)行類型之一。.
注意:我浪費了一些時間在模擬器中測試它不起作用。然而,它在我的手機上工作得很好。

TA貢獻1875條經(jīng)驗 獲得超5個贊
轉(zhuǎn)到Project->Capability->后臺模式->選擇位置更新 轉(zhuǎn)到Project->Info->添加一個鍵NSLocationAlwaysUsageDescription和空值(或者任意文本) 要使位置在后臺工作,并將坐標發(fā)送到Web服務或每5分鐘對它們執(zhí)行任何操作,請按照下面的代碼執(zhí)行。
@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
- 3 回答
- 0 關注
- 613 瀏覽
添加回答
舉報