iOS定時(shí)本地推送

說到推送,項(xiàng)目開發(fā)中有可能會(huì)使用定時(shí)推送.類似鬧鐘,或者提醒事項(xiàng),定個(gè)時(shí)間發(fā)起推送.
使用本地推送和普通推送一樣,也需要注冊推送通知.

在Appdelegate.m中的

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

方法中填寫下放代碼.

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

然后實(shí)現(xiàn)接受本地推送的方法

//接受處理本地推送
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification NS_AVAILABLE_IOS(4_0) {
    //使用UIAlertView顯示推送的消息
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:notification.alertTitle message:notification.alertBody delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
    [alert show];
}

好了,先在我們創(chuàng)建一個(gè)定時(shí)推送.

- (void)setUpLocalNotification:(NSString *)dateStr {
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    if (localNotification == nil) {
        return;
    }
    
    //處理時(shí)間字符串
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm";
    NSDate *fireDate = [formatter dateFromString:dateStr];
    NSAssert(fireDate, @"dateStr類型不匹配,或者為nil");
    
    //設(shè)置UILocalNotification
    [localNotification setTimeZone:[NSTimeZone defaultTimeZone]];//設(shè)置時(shí)區(qū)
    localNotification.fireDate = fireDate;//設(shè)置觸發(fā)時(shí)間
    localNotification.repeatInterval = 0;//設(shè)置重復(fù)間隔
    
    localNotification.alertBody = @"定時(shí)推送的信息";
    localNotification.alertTitle = @"定時(shí)推送";
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    
    //當(dāng)然你也可以調(diào)取當(dāng)前的氣泡,并且設(shè)置.也可以設(shè)置一個(gè)userInfo進(jìn)行傳遞信息
    /*
    [localNotification setApplicationIconBadgeNumber:66];
    localNotification.applicationIconBadgeNumber += 1;
    localNotification.userInfo = @{@"KEY" : @"VALUE"};
     */
    
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

然后給定你的dateStr,就行了

注意的是:dateStr的類型需要和你的dateFormat類型相同,不然fireDate會(huì)為nil.
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容