(七十三)iOS本地推播通知的實現

來源:互聯網
上載者:User

標籤:oc   ios   推送   通知   

iOS的推播通知分為本地推送和網路推送兩種,如果App處於掛起狀態,是可以發送本地通知的,如果已經被殺掉,則只有定時通知可以被執行,而類似於QQ的那種網路訊息推送就無法實現了,因為App的網路模組在被殺掉後是無法執行的,這時候就要藉助遠程通知,通過蘋果的伺服器轉寄通知到手機,本文只介紹本地通知的用法。

①對於iOS8及以上的版本,需要註冊本地通知才能使用,一般在AppDelegate中註冊:

if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeSound categories:nil];        [application registerUserNotificationSettings:settings];}

其中settingsForTypes是一系列可以並列的參數,實現原理就是多個二進位位表示多個功能,每個功能在不同的位,當各個位相或,相應的位被置1,從而開啟功能,這裡開啟的是Alert通知和聲音提示。categories是一個NSSet,官方給出的解釋是通知包含的一系列行為,一般寫nil即可。

②發送一條通知,需要設定alertBody(訊息體),fireDate(發送時間),soundName(提示音,一般填default)。

最後利用UIApplication單例調用scheduleLocalNotification方法發送通知:

UILocalNotification *localNoti = [[UILocalNotification alloc] init];localNoti.alertBody = [NSString stringWithFormat:@"%@:%@",message.fromStr,message.body];localNoti.fireDate = [NSDate date];localNoti.soundName = @"default";[[UIApplication sharedApplication] scheduleLocalNotification:localNoti];
一般的通知都是在應用處於後台時才被發送,因此在發送之前應該判斷是否後台,判斷方法如下:

[UIApplication sharedApplication].applicationState != UIApplicationStateActive



著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

(七十三)iOS本地推播通知的實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.