iOS開發中UILocalNotification實現本地通知實現提醒功能


蘋果手機開發中的信息提示推送方式,一類是遠程服務器推送(APNS)與UILocalNotification本地通知的,下面我來介紹第二種的使用方法。
 
這兩天在做一個鬧鍾提醒功能,用到了本地通知的功能,記錄相關知識如下:

1、本地通知的定義和使用:

本地通知是UILocalNotification的實例,主要有三類屬性:

scheduled time,時間周期,用來指定iOS系統發送通知的時間和日期;

notification type,通知類型,包括警告信息、動作按鈕的標題、應用圖標上的badge(數字標記)和播放的聲音;

自定義數據,本地通知可以包含一個dictionary類型的本地數據。

對本地通知的數量限制,iOS最多允許最近本地通知數量是64個,超過限制的本地通知將被iOS忽略。

    UILocalNotification *notification=[[UILocalNotification alloc] init];
    notification.fireDate=[NSDate dateWithTimeIntervalSinceNow:10];
    notification.alertBody=@"鬧鍾響了。";
    notification.alertTitle=@"請打開鬧鍾";
    notification.repeatInterval=NSCalendarUnitSecond;
   //設置本地通知的時區
    notification.timeZone = [NSTimeZone defaultTimeZone]; notification.applicationIconBadgeNumber
=1; notification.userInfo=@{@"name":@"zhangsanfeng"}; notification.soundName=UILocalNotificationDefaultSoundName; //[[UIApplication sharedApplication]scheduleLocalNotification:notification]; //[[UIApplication sharedApplication]presentLocalNotificationNow:notification];

2、取消本地通知:

        UIApplication *app=[UIApplication sharedApplication];
        NSArray *array=[app scheduledLocalNotifications];
        NSLog(@"%ld",array.count);
        
        for (UILocalNotification * local in array) {
            NSDictionary *dic= local.userInfo;
            if ([dic[@"name"] isEqual:@"zhangsanfeng"]) {
                //刪除指定的通知
                [app cancelLocalNotification:local];
            }
        }
        //也可以使用[app cancelAllLocalNotifications]刪除所有通知;    

3、本地通知的響應:

如果已經注冊了本地通知,當客戶端響應通知時:

    a、應用程序在后台的時候,本地通知會給設備送達一個和遠程通知一樣的提醒,提醒的樣式由用戶在手機設置中設置

    b、應用程序正在運行中,則設備不會(而是應用程序)收到提醒,但是會走應用程序delegate中的方法:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    //如果你想實現程序在后台時候的那種提醒效果,可以在這個方法中添加相關代碼(添加個警告視圖)
}

需要注意的是,在情況a中,如果用戶點擊提醒進入應用程序,也會執行收到本地通知的回調方法,這種情況下如果你添加了上面那段代碼,則會出現連續出現兩次提示,為了解決這個問題,修改代碼如下:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    //判斷應用程序當前的運行狀態,如果是激活狀態,則進行提醒,否則不提醒
    if (application.applicationState == UIApplicationStateActive) {
        //顯示警告內容
    }
}

4、需要注意:What is the difference between presentLocalNotificationNow and scheduleLocalNotification?

There's no difference right here, but using scheduleLocalNotification you can schedule it at whatever time you want, not only in one second. But presentLocalNotificationNow will show one in exactly one second, not in 0.5 or 2.0 in iOS 8, for example.

前提是你的應用程序不處於激活狀態,本地通知才會有效果;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM