2015-06-19 53 views
1

我正在開發一個在後臺工作的應用程序來獲取用戶的位置並使用http請求將其發送到服務器。我的第一個意圖是每隔n分鐘獲取一次用戶的位置,但經過大量研究和試用後,我放棄了,因爲ios在3分鐘後殺死了我的後臺任務。當應用程序處於後臺時獲取用戶位置。 IOS

然後我嘗試了一下MonitoringSignificantLocationChanges,但是由於手機信號塔的使用,它的位置更新不準確,導致我的應用程序失效。

的溶液到以下任一非常感謝:

  1. 獲取在背景用戶的位置每n分鐘無限。
  2. 以高準確度(使用gps)獲取用戶的位置在後臺顯着位置更改
  3. 任何其他具有高精度結果的後臺解決方案。

回答

0

獲取用戶的位置在後臺以高準確度SignificantLocationChanges(使用GPS)

執行以下操作:

的info.plist添加以下

<key>NSLocationAlwaysUsageDescription</key> 
    <string>{your app name} requests your location coordinates.</string> 
    <key>UIBackgroundModes</key> 
    <array> 
     <string>location</string> 
    </array> 

在代碼中使用LoctionManager來獲取位置更新,(它會在前臺和後臺工作)

@interface MyViewController <CLLocationManagerDelegate> 
@property (nonatomic, strong) CLLocationManager *locationManager; 
@end 

@implementation MyViewController 
-(void)startLocationUpdates { 
    // Create the location manager if this object does not 
    // already have one. 
    if (self.locationManager == nil) { 
     self.locationManager = [[CLLocationManager alloc] init]; 
    } 

    self.locationManager.delegate = self; 
    self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; 
    self.locationManager.activityType = CLActivityTypeFitness; 

    // Movement threshold for new events. 
    self.locationManager.distanceFilter = 25; // meters 

    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) { 
     [self.locationManager requestAlwaysAuthorization]; 
    } 
    [self.locationManager startUpdatingLocation]; 
} 

- (void)stopLocationUpdates { 
    [self.locationManager stopUpdatingLocation]; 
} 

#pragma mark CLLocationManagerDelegate 

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { 
    // Add your logic here 
} 
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { 
    NSLog(@"%@", error); 
} 
1

這對我來說是什麼工作,我用CLLocationManagerDelegate,註冊更新上didUpdateLocations和應用程序委託

- (void)applicationDidBecomeActive:(UIApplication *)application { 
    [_locationManager stopMonitoringSignificantLocationChanges]; 
    [_locationManager startUpdatingLocation]; 
} 

我開始更新位置,對我來說,關鍵是當應用程序轉到後臺時,我切換到重要位置更改,以便應用程序不會像這樣排空麪糊:

- (void)applicationDidEnterBackground:(UIApplication *)application { 
    [_locationManager startMonitoringSignificantLocationChanges]; 
} 

在didUpdateLocations,你可以檢查

BOOL isInBackground = NO; 
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) 
{ 
    isInBackground = YES; 
} 

,並開始一個任務在後臺報告的位置,例如

if (isInBackground) { 
    [self sendBackgroundLocationToServer:self.location]; 
} 

,並開始一個任務,我希望幫助。

相關問題