Мониторинг GeoFence не работает с разрешением "WhileInUse". Альтернативой для этого является проверка региона вручную?
У нас есть мониторинг геозоны в нашем приложении для iOS.
До iOS 11 мы только запрашивали AlwaysOn & Never Prompt для разрешения службы определения местоположения.
С iOS 11 теперь у пользователя есть возможность использовать "WhileInUse", при котором любой вид мониторинга региона не будет работать.
Поэтому мы реализовали следующую альтернативу для ручного мониторинга региона следующим образом:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
if([locations count]) {
CLLocation *newLocation = [locations lastObject];
self.latitude = newLocation.coordinate.latitude;
self.longitude = newLocation.coordinate.longitude;
printf("Locatio %f - %f",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
/*
To avoid logging and showing cached locations, we filter the location by timestamp.
We calculate elapsed time since this timestamp property by using timeIntervalSinceNow, and if the elapsed time is more than 60 seconds, filter the location out.
*/
NSTimeInterval interval = [newLocation.timestamp timeIntervalSinceNow];
//check against absolute value of the interval
if (fabs(interval)>60) {
return;
}
/*
horizontalAccuracy is the value indicating which accuracy range (in meters) the location would be in. Say if the value is 20, the actual user’s position can be within a circle with the radius of 20 meters from the location value.
We first validate the horizontalAccuracy to be equal to or more than 0 meter.
Apple’s document says,
*/
if (newLocation.horizontalAccuracy < 0){
return;
}
/*
If horizontalAccuracy is non negative value, we will further examine the value.
In this sample if horizontalAccuracy is more than 150 meters, we filter the location out (which means we log locations with their accuracy value less than 100 meters).
*/
if (newLocation.horizontalAccuracy > 150){
return;
}
_lastLocation = newLocation;
//in meters
}
}
Ниже приведен метод, который будет проверять, находится ли текущее местоположение пользователя внутри какого-либо региона?
-(void)checkIfUserIsInRegion{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSArray *arrGeofence = [GEOFENCE_MANAGER getSavedGeoFences];
for (GeoFencing *geofence in arrGeofence) {
CLLocation *locationGeoFence = [[CLLocation alloc] initWithLatitude:geofence.lattitude.doubleValue longitude:geofence.longitude.doubleValue];
//Get Distance of current location & set Geofence Location
double distance = [[CasinoLocationManager sharedInstance].lastLocation distanceFromLocation:locationGeoFence];
//Get Already Detected GeoFence list
Boolean isEnteredBefore = [[GeoFenceManager sharedInstance] checkIfGeoFenceExist:[NSString stringWithFormat:@"%f",geofence.geoFencingIdentifier]];
//If Distance is within expected radius then consider as Enter
if(distance<=geofence.radius){
//Check in localy stored Geofence which are already detected and synced with server
if(!isEnteredBefore){
[[GeoFenceManager sharedInstance] notifyWebForGeoFenceRegion:geofence.region state:CLRegionStateInside];
}
}{
//If Distance is not within expected radius then consider as Exit
//If region is considered Inside before then set them exit and sync to server
if(isEnteredBefore){
[[GeoFenceManager sharedInstance] notifyWebForGeoFenceRegion:geofence.region state:CLRegionStateOutside];
}
}
}
});
//
}
Дайте мне знать, если это будет правильный подход, который не приведет к отклонению моего приложения в магазине приложений. Также хочу узнать, где будет стандартное место для вызова моего следующего метода, который во всех случаях синхронизирует все состояния области геозоны с минимальным временем...
checkIfUserIsInRegion ()
Спасибо заранее. Любое предложение или улучшение или идея приветствуются.