我刚刚下载了Xcode并尝试制作本地通知示例。问题是,本地通知在模拟器中是否有效?
谢谢
是的,本地通知可以在模拟器上使用。但是,如果您希望在应用程序前台看到通知,请确保在应用委托中实现了application:didreceiveLocalNotification
:
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"MyAlertView"
message:notification.alertBody
delegate:self cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
if (alertView) {
[alertView release];
}
}
否则,请确保您在未来的某个时间安排通知,然后关闭应用程序,以便查看苹果的示例工作:
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil) return;
NSDate *fireTime = [[NSDate date] addTimeInterval:10]; // adds 10 secs
localNotif.fireDate = fireTime;
localNotif.alertBody = @"Alert!";
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
很容易认为你没有正确实现测试代码,而且在应用程序运行时你没有处理事件。
如果你遇到了这个旧问题,可能会遇到另一个坑点:iOS 8引入了新的通知权限,你的应用程序必须明确地请求它们。
在你的AppDeligate.m
文件中:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//register local notifications
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
//the rest of your normal code
return YES;
}
如果你不这样做,你的通知将永远不会触发,并且你将在日志中收到像这样的精彩消息:尝试调度一个带警报的本地通知 <UIConcreteLocalNotification: 0x7ae51b10>{...警报详情...},但还没有获得用户显示警报的权限
本地通知在模拟器上可用,推送通知则不行。
应用程序设置通知部分未显示
我也遇到了这个问题。似乎发生了以下情况:
UNUserNotificationCenter.current().requestAuthorization
等)。重置应用状态
之后我再次启动了应用,通知设置仍然显示(由于我拒绝了权限,所以显示为关闭)。
要重置这个并重新产生原始问题,我必须执行以下操作:
xcrun simctl uninstall booted com.app.bundlename
(请参见如何在每次运行单元测试时运行应用程序的全新安装?)。