【问题标题】:Updating Location every x seconds iOS每 x 秒更新一次位置 iOS
【发布时间】:2017-04-21 08:32:01
【问题描述】:

我正在尝试构建一个 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]];

}

【问题讨论】:

  • 当位置管理员可以在位置更改时通知您,为什么要每 x 秒更新一次。
  • 即使它没有改变,我也需要它在一个区间内
  • 这不是 CoreLocation 的工作方式。因此,您将不得不伪造它。将最新位置存储在变量中,并每隔 x 秒读取一次。
  • 这段代码是在 appdelegate 还是 viewcontroller 中?
  • 请参考这个你会得到一个想法stackoverflow.com/questions/6347503/…

标签: ios objective-c location


【解决方案1】:

试试这个:

在 .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");
    }
}

【讨论】:

    【解决方案2】:

    使用 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.
    
    }
    

    【讨论】:

    • 请问我现在有什么问题...?我在我的应用程序中每 5 秒更新一次......它对我来说工作正常......
    【解决方案3】:

    在 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];
    });
    

    【讨论】:

    • 变量 app 是什么?
    • chogath 抱歉,我忘了添加 AppDelegate.h 代码。 @interface AppDelegate : UIResponder { CLLocationManager *locationManager; UIApplication *应用程序; }
    • 我创建了一个新项目并复制了您的代码,但控制台中没有显示任何内容!
    • 要在应用程序运行时启用位置更新权限,需要特殊密钥。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多