我正在尝试监控用户的重要位置更改。所以我在应用程序中订阅了重要的位置更改事件,但我没有将代理(我编写代码以发送本地通知的位置)分配给位置管理器。我不知道以下代码的工作原理。
的ViewController
- (void)viewDidLoad {
[super viewDidLoad];
if (nil == locationManager){
locationManager = [[CLLocationManager alloc] init];
if ([locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
[locationManager setAllowsBackgroundLocationUpdates:YES];
}
}
locationManager.delegate = self;
if([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]){
[locationManager requestAlwaysAuthorization];
[locationManager startMonitoringSignificantLocationChanges];
}
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
CLLocation* location = [locations lastObject];
NSLog(@"latitude %+.6f, longitude %+.6f\n",
location.coordinate.latitude,
location.coordinate.longitude);
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
localNotification.alertBody = @"Your alert message";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
的AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey]) {
CLLocationManager *locationManager = [[CLLocationManager alloc]init];
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
locationManager.activityType = CLActivityTypeOtherNavigation;
[locationManager startMonitoringSignificantLocationChanges];
}
return YES;
}
根据文件here。使用这些服务的应用程序可以在新的位置事件到达时终止并随后重新启动。虽然应用程序本身已重新启动,但位置服务不会自动启动。要获取该数据,您必须创建一个新的CLLocationManager对象,并在应用程序终止之前重新启动您运行的位置服务。当您重新启动这些服务时,位置管理器会将所有挂起的位置更新传递给其代理。
但是在app delegate中我没有将任何委托分配给位置管理器的新实例,我仍然收到通知。
答案 0 :(得分:0)
看起来您正在分配两个不同的locationManager
实例,它们以独立的方式运行。您需要将其更改为:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
...
if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey]) {
// Notify the app's UI to instantiate your viewController
// that then re-initialises its own locationManager.
}
return YES;
}