Я пытаюсь найти местоположения пользователей на переднем плане & фон. Мне нужно вызвать api после обновления локации. Для работы в фоновом режиме я хочу использовать метод «Отсрочка». Я следил за тем же процессом, как описано в Apple WWDC. Я проверяю приложение на iPhone 5 (iOS 7). Он работает нормально, когда я нахожусь на переднем плане, но не дал мне обновления после отправки приложения в фоновом режиме. Ниже приведен код, который я использую, чтобы получить местоположение в фоновом режиме.deffered Обновления местоположения не доступны
#import "AppDelegate.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.locationArray = [[NSMutableArray alloc] init];
self.locationErrorArray = [[NSMutableArray alloc] init];
self.manager_loc = [[CLLocationManager alloc] init];
self.manager_loc.activityType = CLActivityTypeFitness;
self.manager_loc.delegate = self;
[self.manager_loc setDesiredAccuracy:kCLLocationAccuracyBest];
[self.manager_loc startUpdatingLocation];
return YES;
}
- (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.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// 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.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// 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.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
#pragma mark - Location Manager Delgate
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"update failed");
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
[self.locationArray addObject:locations];
NSLog(@"udate locations %f %f", manager.location.coordinate.latitude, manager.location.coordinate.longitude);
if (!self.deferredStatus)
{
self.deferredStatus = YES;
[self.manager_loc allowDeferredLocationUpdatesUntilTraveled:100 timeout:30];
}
[self.manager_loc stopUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didFinishDeferredUpdatesWithError:(NSError *)error
{if (manager.location != nil)
{ [self.locationArray addObject:manager.location];
}
if (error != nil)
{
[self.locationErrorArray addObject:error.description];
}
self.deferredStatus = NO;
NSLog(@"deffered success %f %f", manager.location.coordinate.latitude, manager.location.coordinate.longitude);
}
@end
Если я не остановить обновление местоположения в didUpdateToLocations делегатом затем местоположение стрелка (в строке состояния) не идут. В этом случае он дает мне места contionusly. Я хочу обновление местоположения по истечении определенного времени или пройденного расстояния, чтобы я мог поразить сервер с помощью локаций пользователя. Пожалуйста помоги мне с этим.
В iOS7 [locationmanager startupdatinglocation] не работает в фоновом режиме. Если я запускаю диспетчер местоположений на переднем плане и не останавливаю его в updateToLocations: делегат, то знак стрелки (в строке состояния) не исчезает. В этом сценарии я получаю местоположение после того, как я путешествовал на определенном расстоянии, но он очень быстро разряжает батарею. Можете ли вы предоставить мне альтернативный код для достижения желаемой цели. – user3073979