每x秒iOS更新位置

时间:2017-04-21 08:32:01

标签: ios objective-c location

我正在尝试构建iOS,我可以每隔x秒更新一次我的位置并发送通知以更新UI。 我得到了我的位置,但更新是随机的。任何想法如何添加间隔?

这是我的代码:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = [locations lastObject];
    [self sendNotification :@"long"
                           :[NSString stringWithFormat:@"%.8f",location.coordinate.longitude]];
    [self sendNotification :@"lat"
                           :[NSString stringWithFormat:@"%.8f",location.coordinate.latitude]];

}

3 个答案:

答案 0 :(得分:0)

使用NSTimer:

//声明全局

NSTimer *ShareTimeCheck;
    int ShareSecLeft;

实施此方法:

  -(void)shareTimeChecking{
        if (ShareSecLeft==0) {
            [ShareTimeCheck invalidate];
            ShareTimeCheck=nil;
        }else{
            ShareSecLeft--;
            if (ShareSecLeft==0) {
                [ShareTimeCheck invalidate];
                ShareTimeCheck=nil;
            }
        }
    }

在您的位置更新方法中调用此方法:

                    if (ShareSecLeft==0) {
        [ShareTimeCheck invalidate];
                        ShareTimeCheck=nil;
                        ShareSecLeft=5;

    heduledTimerWithTimeInterval:1 target:self selector:@selector(shareTimeChecking) userInfo:nil repeats:YES];

  //write ur code to update the ui. or update to server as per ur requirement.

}

答案 1 :(得分:0)

在iOS本机中,我们无法更改系统更新用户位置的时间间隔。如果有GPS信号,IOS会每秒定期更新位置。

如果应用程序位于前台,我们可以简单地停止监视并在间隔后再次启动它,例如使用NSTimer。在这种情况下,我们必须考虑应用程序的生命周期。应用程序在后台运行并在空闲停止工作期间运行。

我的最后一个程序是使用UIApplication:beginBackgroundTaskWithExpirationHandler:在后台使用NSTimer。应用程序在后台运行时,此计时器会定期触发。您可以查看以下示例:

#import "AppDelegate.h"

@implementation AppDelegate

BOOL locationStarted = FALSE;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //set default value after application starts
    locationStarted = FALSE;
    //create CLLocationManager variable
    locationManager = [[CLLocationManager alloc] init];
    //set delegate
    locationManager.delegate = self;

    app = [UIApplication sharedApplication];

    return YES;
}

//update location
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    NSLog(@"Location: %f, %f", newLocation.coordinates.longtitude, newLocation.coordinates.latitude);
}

//run background task
-(void)runBackgroundTask: (int) time{
    //check if application is in background mode
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) {

        //create UIBackgroundTaskIdentifier and create a background task, which starts after time
        __block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
            [app endBackgroundTask:bgTask];
            bgTask = UIBackgroundTaskInvalid;
        }];

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            NSTimer* t = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(startTrackingBg) userInfo:nil repeats:NO];
            [[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
            [[NSRunLoop currentRunLoop] run];
        });
    }
}

//starts when application switches to background
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    //check if application status is in background
    if ( [UIApplication sharedApplication].applicationState == UIApplicationStateBackground) {
        NSLog(@"start background tracking from appdelegate");

        //start updating location with location manager
        [locationManager startUpdatingLocation];
    }

    //change locationManager status after time
    [self runBackgroundTask:20];
}

//starts with background task
-(void)startTrackingBg{
    //write background time remaining
    NSLog(@"backgroundTimeRemaining: %.0f", [[UIApplication sharedApplication] backgroundTimeRemaining]);

    //set default time
    int time = 60;
    //if locationManager is ON
    if (locationStarted == TRUE ) {
        //stop update location
        [locationManager stopUpdatingLocation];
        locationStarted = FALSE;
    }else{
        //start updating location
        [locationManager startUpdatingLocation];
        locationStarted = TRUE;
        //ime how long the application will update your location
        time = 5;
    }

    [self runBackgroundTask:time];
}

//application switches back from background
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    locationStarted = FALSE;
    //stop updating
    [locationManager stopUpdatingLocation];
}

/*** other methods ***/
- (void)applicationWillResignActive:(UIApplication *)application{}

- (void)applicationDidBecomeActive:(UIApplication *)application{}

- (void)applicationWillTerminate:(UIApplication *)application{}

@end

更简单的解决方案可能是运行定时器循环:

__block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    NSTimer* t = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(startTrackingBg) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
});

答案 2 :(得分:0)

试试这个:

在.h文件中声明

@property (strong, nonatomic) NSDate *lastTimestamp;

- (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(@"update your UI");
    }
}