iOS8 本地推送 UILocalNotification

前言

最近忙中偷閑,把有關(guān)本地推送的內(nèi)容給整理一下,本篇文章主要講述UILocalNotification的一些使用,下篇文章會在此基礎(chǔ)上介紹其替代品UNUserNotificationCenter。

UILocalNotification的使用

在iOS8及其之后的推送都使用UILocalNotification來實現(xiàn),有關(guān)于UILocalNotification的介紹我們可以在其框架中可見。

// In iOS 8.0 and later, your application must register for user notifications using -[UIApplication registerUserNotificationSettings:] before being able to schedule and present UILocalNotifications
NS_CLASS_DEPRECATED_IOS(4_0, 10_0, "Use UserNotifications Framework's UNNotificationRequest") __TVOS_PROHIBITED
@interface UILocalNotification : NSObject<NSCopying, NSCoding>

在官方的解釋中指出了UILocalNotification應(yīng)該如何使用:在iOS8.0及更高的版本中,你的應(yīng)用程序如果想要顯示通知就必須使用-[UIApplication registerUserNotificationSettings:]注冊用戶通知

那么到此為止,我們關(guān)于本地推送的任務(wù)只需要兩步就可以搞定了:

  1. 使用-[UIApplication registerUserNotificationSettings:]注冊通知;
  2. 實現(xiàn)推送通知內(nèi)容

1. 使用-[UIApplication registerUserNotificationSettings:]注冊通知

注冊通知的位置可以隨意,只要步驟2之前就可以了。不過習(xí)慣性我們都會講注冊通知一類的放在程序啟動的時候,即放在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions函數(shù)中。

在上述的官方解釋中提到了注冊通知是要使用-[UIApplication registerUserNotificationSettings:]來實現(xiàn)的,又因為其是個實例方法(-方法),故應(yīng)使用UIApplication的實例對象調(diào)用該方法。

[[UIApplication sharedApplication] registerUserNotificationSettings:<#(nonnull UIUserNotificationSettings *)#>];

函數(shù)調(diào)用出來了,問題來了,這里調(diào)用的-registerUserNotificationSettings:這個函數(shù)還需要一個UIUserNotificationSettings類型的參數(shù),我們來查看一下這個類。

@interface UIUserNotificationSettings : NSObject

// categories may be nil or an empty set if custom user notification actions will not be used
+ (instancetype)settingsForTypes:(UIUserNotificationType)types
                      categories:(nullable NSSet<UIUserNotificationCategory *> *)categories; // instances of UIUserNotificationCategory

@property (nonatomic, readonly) UIUserNotificationType types;

// The set of UIUserNotificationCategory objects that describe the actions to show when a user notification is presented
@property (nullable, nonatomic, copy, readonly) NSSet<UIUserNotificationCategory *> *categories;

@end

UIUserNotificationSettings類繼承自NSObject,有一個類方法(+方法)用以初始化,此方法中包含了兩個參數(shù)types和categories。

  1. types: 這個參數(shù)是一個UIUserNotificationType的枚舉,如下所示:
typedef NS_OPTIONS(NSUInteger, UIUserNotificationType) {
    UIUserNotificationTypeNone    = 0,      // the application may not present any UI upon a notification being received
    UIUserNotificationTypeBadge   = 1 << 0, // the application may badge its icon upon a notification being received
    UIUserNotificationTypeSound   = 1 << 1, // the application may play a sound upon a notification being received
    UIUserNotificationTypeAlert   = 1 << 2, // the application may display an alert upon a notification being received
} NS_ENUM_DEPRECATED_IOS(8_0, 10_0, "Use UserNotifications Framework's UNAuthorizationOptions") __TVOS_PROHIBITED;

其具體意思就是說當(dāng)應(yīng)用程序收到通知的時候是否要更改顯示程序角標(biāo)、是否播放聲音、是否彈框提醒等。

  1. categories: 這個參數(shù)在類方法的說明中就已經(jīng)說明了,如果不適用自定義用戶通知操作,可以設(shè)為nil。

到這里推送的注冊代碼就已經(jīng)可以寫出來了:

// 此種通知只適用于iOS8.0及更高版本,故加個判斷
if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
        // 設(shè)置通知類型
        UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound) categories:nil];
        // 授權(quán)通知
        [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
    }

2. 實現(xiàn)推送通知內(nèi)容

要使用UILocalNotification實現(xiàn)推送功能,我們首先可以查看一下該類的組成:

@interface UILocalNotification : NSObject<NSCopying, NSCoding>

// 初始化方法
- (instancetype)init NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;

// timer-based scheduling
// 推送發(fā)送時間
@property(nullable, nonatomic,copy) NSDate *fireDate;
// the time zone to interpret fireDate in. pass nil if fireDate is an absolute GMT time (e.g. for an egg timer).
// pass a time zone to interpret fireDate as a wall time to be adjusted automatically upon time zone changes (e.g. for an alarm clock).
// 推送時間所屬時區(qū)的設(shè)置
@property(nullable, nonatomic,copy) NSTimeZone *timeZone;

// 重復(fù)時間
@property(nonatomic) NSCalendarUnit repeatInterval;      // 0 means don't repeat
@property(nullable, nonatomic,copy) NSCalendar *repeatCalendar;

// location-based scheduling

// set a CLRegion object to trigger the notification when the user enters or leaves a geographic region, depending upon the properties set on the CLRegion object itself. registering multiple UILocalNotifications with different regions containing the same identifier will result in undefined behavior. the number of region-triggered UILocalNotifications that may be registered at any one time is internally limited. in order to use region-triggered notifications, applications must have "when-in-use" authorization through CoreLocation. see the CoreLocation documentation for more information.
@property(nullable, nonatomic,copy) CLRegion *region NS_AVAILABLE_IOS(8_0);

// when YES, the notification will only fire one time. when NO, the notification will fire every time the region is entered or exited (depending upon the CLRegion object's configuration). default is YES.
@property(nonatomic,assign) BOOL regionTriggersOnce NS_AVAILABLE_IOS(8_0);

// alerts
// 彈出內(nèi)容
@property(nullable, nonatomic,copy) NSString *alertBody;      // defaults to nil. pass a string or localized string key to show an alert
@property(nonatomic) BOOL hasAction;                // defaults to YES. pass NO to hide launching button/slider
@property(nullable, nonatomic,copy) NSString *alertAction;    // used in UIAlert button or 'slide to unlock...' slider in place of unlock
@property(nullable, nonatomic,copy) NSString *alertLaunchImage;   // used as the launch image (UILaunchImageFile) when launch button is tapped
@property(nullable, nonatomic,copy) NSString *alertTitle NS_AVAILABLE_IOS(8_2);  // defaults to nil. pass a string or localized string key

// sound
@property(nullable, nonatomic,copy) NSString *soundName;      // name of resource in app's bundle to play or UILocalNotificationDefaultSoundName

// badge
@property(nonatomic) NSInteger applicationIconBadgeNumber;  // 0 means no change. defaults to 0

// user info
@property(nullable, nonatomic,copy) NSDictionary *userInfo;   // throws if contains non-property list types

// category identifer of the local notification, as set on a UIUserNotificationCategory and passed to +[UIUserNotificationSettings settingsForTypes:categories:]
@property (nullable, nonatomic, copy) NSString *category NS_AVAILABLE_IOS(8_0);

@end

該類中包含了兩個初始化方法- init- initWithCoder:以及很多的成員變量,這些成員變量就是發(fā)送通知的一些設(shè)置。關(guān)于部分成員變量的作用我直接在上面的代碼中標(biāo)注了(有些英文標(biāo)注很清楚,就此略過)。下面就可以直接創(chuàng)建通知。

            // 創(chuàng)建通知
            UILocalNotification *localNotification = [[UILocalNotification alloc] init];
            // 設(shè)置通知的必選參數(shù)
            // 設(shè)置通知顯示的內(nèi)容
            localNotification.alertBody = @"我來找你咯";
            // 設(shè)置通知發(fā)送的時間(這里設(shè)置的是當(dāng)前時間延遲10s發(fā)送,創(chuàng)建通知我是放在按鈕點擊事件中了,點擊之后,按home鍵等待10s即可收到推送)
            localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
            // 解鎖滑動時的事件
            localNotification.alertAction = @"磨蹭啥呢";
            // 收到推送通知時APP icon角標(biāo),這里如果設(shè)置了,那么在應(yīng)用程序即將啟動的時候要記得把角標(biāo)清空
            localNotification.applicationIconBadgeNumber = 1;
            // 推送是帶有聲音提醒的,設(shè)置默認的字段為 UILocalNotificationDefaultSoundName
            localNotification.soundName = UILocalNotificationDefaultSoundName;
            // 發(fā)送通知
            // 方式一:根據(jù)通知的發(fā)送時間(fireDate)發(fā)送通知
            [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
            // 方式二:立即發(fā)送通知
//            [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];

推送創(chuàng)建中還有很多參數(shù),比如推送消息中包含圖片等等,可以沒事自己嘗試一下,我這里只是搞了個最簡單的。

總結(jié)

關(guān)于UILocalNotification實現(xiàn)本地推送的介紹就完了。我介紹的時候并不是直接告訴你應(yīng)該怎么使用,而是告訴你應(yīng)該怎么樣才能更好的去學(xué)習(xí)一個新的類(東西),并不是看看別人怎么用的,然后自己拿過來直接使用就OK了,那樣是不行的。

授人以魚不如授人以漁。在你碰到一個新東西的時候,并不是要著急著去網(wǎng)上找關(guān)于這個東西的使用方法及其介紹,相反的我們可以自己通過查看其英文注釋(我英語很差,但是需要耐著性子慢慢看,遇到不認識的單詞谷歌一下,慢慢的你就能看懂咯)或者了解類的構(gòu)造等各種方法來深入剖析其應(yīng)該怎么使用以及其功能等等。

我認為我就是在一本正經(jīng)的胡說八道 ??????

友情鏈接:iOS10 本地推送 UNUserNotificationCenter

最后編輯于
?著作權(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)容

  • 極光推送: 1.JPush當(dāng)前版本是1.8.2,其SDK的開發(fā)除了正常的功能完善和擴展外也緊隨蘋果官方的步伐,SD...
    Isspace閱讀 6,884評論 10 16
  • 推送通知 注意:這里說的推送通知跟NSNotification有所區(qū)別 NSNotification是抽象的,不可...
    iOS開發(fā)攻城獅閱讀 4,419評論 1 13
  • 概述 在多數(shù)移動應(yīng)用中任何時候都只能有一個應(yīng)用程序處于活躍狀態(tài),如果其他應(yīng)用此刻發(fā)生了一些用戶感興趣的那么通過通知...
    莫離_焱閱讀 6,717評論 1 8
  • 推送通知注意:這里說的推送通知跟NSNotification有所區(qū)別NSNotification是抽象的,不可見的...
    醉葉惜秋閱讀 1,616評論 0 3
  • 許多集成的步驟個推官網(wǎng)都有了,這里只寫關(guān)于推送的遠程推送和本地通知的步驟和代碼。APP在后臺時:走蘋果的APNS通...
    AllureJM閱讀 2,965評論 1 9

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