在didStartMonitoringFor

时间:2019-01-29 16:13:49

标签: ios objective-c core-location geofencing

对于为什么我的AppDelegate CLLocationManager有时无法成功确定CLRegionState(CLRegionState.unknown)感到困惑,尽管我确保直到requestStateForRegion之后才调用didStartMonitoringForRegion。好像是某种比赛条件,我不明白自己没有处理。

相关,当我获得CLRegionState.unknown时该怎么办?不断请求状态,直到我得到一些东西? (这似乎很糟糕)

AppDelegate:

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{   
    self.locationManager = [[CLLocationManager alloc] init];
    [self.locationManager setDelegate:self];

    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(nonnull CLRegion *)region {
    NSLog(@"%@", [NSString stringWithFormat:@"didStartMonitoringFor region with ID: %@", region.identifier]);
    // delay per https://stackoverflow.com/a/33288103/3380970
    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
        [self.locationManager requestStateForRegion:region];
    });
}

- (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(nonnull CLRegion *)region {
    NSLog(@"%@", [NSString stringWithFormat:@"didDetermineState from AppDelegate CLLocationManager: %@ (%ld)", region.identifier, (long)state ]);
    NSString *baseUrl = [self fetchBaseUrl];
    switch (state) {
        case CLRegionStateInside:
            NSLog(@"%@", @"Determined .inside state for geofence");
            [HelperFunctions postGeofenceTransitionWithBaseUrl:baseUrl region:region transitionType:1];
            break;
        default:
            break;
    }
}

摘要日志:

Adding geofence with ID: 5:90fd74e0-cbc7-dbe5-20fc-b870203055e1    
Adding geofence with ID: 8:d408f466-ea1b-6cbb-382f-f7567db61157
Adding geofence with ID: 7:ba97dda2-39a7-9b95-8ea9-ea183d69a858

didStartMonitoringFor region with ID: 5:90fd74e0-cbc7-dbe5-20fc-b870203055e1
didStartMonitoringFor region with ID: 8:d408f466-ea1b-6cbb-382f-f7567db61157
didStartMonitoringFor region with ID: 7:ba97dda2-39a7-9b95-8ea9-ea183d69a858

didDetermineState from AppDelegate CLLocationManager: 5:90fd74e0-cbc7-dbe5-20fc-b870203055e1 (0)
didDetermineState from AppDelegate CLLocationManager: 8:d408f466-ea1b-6cbb-382f-f7567db61157 (0)
didDetermineState from AppDelegate CLLocationManager: 7:ba97dda2-39a7-9b95-8ea9-ea183d69a858 (0)

谢谢

1 个答案:

答案 0 :(得分:1)

这是因为您在块内使用了输入参数region而没有使它成为块变量。

- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(nonnull CLRegion *)region {中添加:

__block CLRegion *blockRegion = region;

并在您的屏蔽内使用blockRegion