博客> iOS注册本地通知
iOS注册本地通知
2019-10-11 12:46 评论:0 阅读:926 Sherry_ssq
ios 本地通知

首先在AppDelegate里面注册本地通知

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
    [application registerUserNotificationSettings:setting];

    return YES;
}

在ViewController控制器中写上需要通知的内容及时间

//设置10秒之后
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:10];

    UILocalNotification *noti = [[UILocalNotification alloc] init];

    if (noti) {

        //设置推送时间

        noti.fireDate = date;//=now

        //设置时区

        noti.timeZone = [NSTimeZone defaultTimeZone];

        //设置重复间隔

        noti.repeatInterval = NSWeekCalendarUnit;

        //推送声音

        noti.soundName = UILocalNotificationDefaultSoundName;

        //内容

        noti.alertBody = @"推送内容";

        //显示在icon上的红色圈中的数子

        noti.applicationIconBadgeNumber = 1;

        //设置userinfo 方便在之后需要撤销的时候使用

        NSDictionary *infoDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];

        noti.userInfo = infoDic;

        //添加推送到uiapplication

        UIApplication *app = [UIApplication sharedApplication];

        [app scheduleLocalNotification:noti];

    }   

在AppDelegate里面接收通知内容

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification*)notification

{
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); //震动

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"接收到本地提醒 in app"

                                                    message:notification.alertBody

                                                   delegate:nil

                                          cancelButtonTitle:@"确定"

                                          otherButtonTitles:nil];

    [alert show];

    //这里,你就可以通过notification的userInfo,干一些你想做的事情了
    application.applicationIconBadgeNumber -= 1;
}
收藏
1
sina weixin mail 回到顶部