iOS8+ 本地通知

從iOS8開始,通知被加入了新的特性。簡單地說,從現(xiàn)在開始,當(dāng)一個通知被展示時,開發(fā)者可以指定用戶可觸發(fā)的具體的動作(actions),而且甚至不用啟動App也可以處理這個通知。

有幾種方式來提示用戶一個通知,接下來會展示所有支持的通知類型。正如你已經(jīng)了解的,你可以指定通知類型為他們中的幾個或者所有。

  1. Alert or Banner:通知可以用alert或者banner來顯示,這取決于用戶在設(shè)置中得選擇。他們都應(yīng)當(dāng)包含通知的消息(當(dāng)然是可以本地化的)。
  2. 聲音(Sound):當(dāng)一個通知被送達(dá)時,你可以‘告訴’iOS播放一段自定義或者系統(tǒng)默認(rèn)的聲音。因為用戶不會一直看著設(shè)備,被展示的通知有可能會被忽略,所以聲音顯得很有用。但是,對于不重要的通知,聲音不應(yīng)該被使用。
  3. Badge:當(dāng)通知到達(dá)時,一個badge數(shù)字會在App的圖標(biāo)上顯示。當(dāng)一個通知到達(dá)時,badge數(shù)字必增加1,當(dāng)通知被處理后badge數(shù)字減1。當(dāng)badge數(shù)字不為0或者為0,iOS會顯示或者隱藏badge。

在iOS8之后,以前的本地推送寫法可能會出錯,接收不到推送的信息,
如果出現(xiàn)以下信息:

1 Attempting to schedule a local notification
2 with an alert but haven't received permission from the user to display alerts
3 with a sound but haven't received permission from the user to play sounds

在IOS8下沒有注冊,所以需要額外添加對IOS8的注冊方法,API中有下面這個方法:

// Registering UIUserNotificationSettings more than once results in previous settings being overwritten.  
- (void)registerUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings NS_AVAILABLE_IOS(8_0);  

ios8后,需要添加這個注冊,才能得到授權(quán)

  if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {  
    UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;  
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type  
                                                                             categories:nil];  
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];  
    // 通知重復(fù)提示的單位,可以是天、周、月  
    notification.repeatInterval = NSCalendarUnitDay;  
  } else {  
    // 通知重復(fù)提示的單位,可以是天、周、月  
    notification.repeatInterval = NSDayCalendarUnit;  
  }

本地通知回調(diào)函數(shù),當(dāng)應(yīng)用程序在前臺時調(diào)用,此方法在AppDelegate中

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

在不需要再推時,可以取消推送cancelLocalNotificationWithKey:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容