我对 iOS 开发相当陌生,我正在尝试创建一个允许区域监控的应用程序。类似于 iOS 提醒应用程序。
我的代码已经到了开始监视区域的地步,它应该在我进入和离开某个区域时通知我。但是,它只告诉我我何时在该地区。当我离开时,它没有告诉我。
你知道,我正在我的 iPhone 上测试这个,并且肯定超出了 100m 的半径(我开车离开我家 10 分钟)。它不断循环消息说我在该地区,但当我离开该地区时从未改变。我真的很困惑我哪里出错了。任何人都可以帮忙吗?另外,出于好奇,由于我是 iOS 开发的新手,我是否以正确的方式进行此操作?或者有没有更有效的方法来实现这一点?任何建议,教程,howto's 将不胜感激。多谢你们!我的启动区域监控的代码和方法如下。如果您需要任何其他代码,请告诉我。
(IBAction)addRegion:(id)sender {
if ([CLLocationManager isMonitoringAvailableForClass:[CLBeaconRegion class]]) {
// Create a new region based on the center of the map view.
CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(_mapView.centerCoordinate.latitude, _mapView.centerCoordinate.longitude);
region = [[CLCircularRegion alloc] initWithCenter:coord
radius:Radius
identifier:[NSString stringWithFormat:@"%f, %f", _mapView.centerCoordinate.latitude, _mapView.centerCoordinate.longitude]];
// Start monitoring the newly created region.
[_locationManager startMonitoringForRegion:(CLRegion *)region];
}
else {
NSLog(@"Region monitoring is not available.");
}
}
(IBAction)stopMonitoringRegion:(id)sender {
[_locationManager stopMonitoringForRegion:(CLRegion *)region];
}
(void)locationManager:(CLLocationManager *)manager
didDetermineState:(CLRegionState)state forRegion:(CLRegion *)reg {
if (state == CLRegionStateInside) {
//call didEnterRegion
//[_locationManager stopMonitoringForRegion:region];
[self locationManager:_locationManager didEnterRegion:region];
}
if (state == CLRegionStateOutside) {
//call didExitRegion
//[_locationManager stopMonitoringForRegion:region];
[self locationManager:_locationManager didExitRegion:region];
}
}
(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(@"didFailWithError: %@", error);
}
(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
//requestStateForRegion
if (region == nil) {
//do nothing
NSLog(@"didUpdateToLocation %@ from %@", newLocation, oldLocation);
}else{
[_locationManager requestStateForRegion:region];
NSLog(@"didUpdateToLocation %@ from %@", newLocation, oldLocation);
}
}
(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
NSLog(@"didEnterRegion %@ at %@", region.identifier, [NSDate date]);
}
(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
NSLog(@"didExitRegion %@ at %@", region.identifier, [NSDate date]);
}
(void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error {
NSLog(@"monitoringDidFailForRegion %@: %@ Error: %@", region.identifier, [NSDate date], error);
}