在发出本地通知时询问用户是否允许显示警报

use*_*316 13 xcode alert uialertview ios uilocalnotification

我希望在本地通知被触发时显示警告,但为此我必须请求许可,因为当我在iPhone上运行应用程序时,它对我说:

尝试安排本地通知{开火日期= 2014年6月13日星期五12小时10分27秒中欧夏令时,时区=(null),重复间隔= 0,重复计数= UILocalNotificationInfiniteRepeatCount,下次开火日期= 2014年6月13日星期五12小时10分27秒中欧夏令时,用户信息=(null)}带有提醒但未收到用户显示提醒的权限

我怎样才能做到这一点?这是现在的代码:

    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    localNotif.fireDate = [[NSDate date] dateByAddingTimeInterval:timeUntilNotification];
    localNotif.soundName = UILocalNotificationDefaultSoundName;
    localNotif.alertBody = @"ZEIT!";
    localNotif.alertAction = @"Show me the Timer!";
    localNotif.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] +1;


    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
Run Code Online (Sandbox Code Playgroud)

蘇健豪*_*蘇健豪 40

添加此代码后,它将显示警报视图以询问用户是否允许.

if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeSound|UIUserNotificationTypeBadge
                                                                                                          categories:nil]];
}
Run Code Online (Sandbox Code Playgroud)

您可以在应用程序中添加此代码:didFinishLaunchingWithOptions; 方法,以便应用程序在启动应用程序时询问您的用户,或者您可以在设置本地通知时添加此代码,这取决于您.

  • 这个片段很棒,谢谢!请大家注意:在您的应用中专门想要让用户发送通知的权限时,请仔细考虑,因为您不想在打开应用时立即将其吓跑.先建立一些信任,然后征得他们的同意.UX思考的食物:) (3认同)