【发布时间】:2016-10-06 07:56:48
【问题描述】:
我正在尝试为我的用户监控重大的位置变化。所以我已经订阅了应用程序中的重大位置更改事件,但我没有将委托(我编写代码以触发本地通知的地方)分配给位置管理器。我不明白为什么以下代码有效。
视图控制器
- (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中实现了delegate callbacks。ViewController是在其中创建viewDidLoadlocationManager是rootViewController还是在您启动应用程序后被实例化。 -
不,我还没有在应用程序委托中实现委托回调,但是 ViewController 是我的 rootViewController
-
由于您使用
storyboard来加载rootViewController。viewDidLoad在您启动应用程序时立即触发,因此您将获得委托回调。 -
你解决了吗?
标签: ios objective-c notifications core-location uilocalnotification