點擊 iOS 接收遠程推送主要牽扯到的方法有以下五種
(1) - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
(2) - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
(3) - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
(4) - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
(5) - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
- 會在app啟動完成調用
launchOptions
保存了app啟動的原因信息,如果app是因為點擊通知欄啟動的,可以在launchOptions
獲取到通知的具體內容。 - 會在接收到通知的時候調用,在最新的iOS 10中已經廢棄,建議不再使用。
- 是在iOS 7之后新增的方法,可以說是 2 的升級版本,如果app最低支持iOS 7的話可以不用添加 2了。
其中completionHandler
這個block可以填寫的參數UIBackgroundFetchResult
是一個枚舉值。主要是用來在后臺狀態下進行一些操作的,比如請求數據,操作完成之后,必須通知系統獲取完成,可供選擇的結果有
typedef NS_ENUM(NSUInteger, UIBackgroundFetchResult) {
UIBackgroundFetchResultNewData,
UIBackgroundFetchResultNoData,
UIBackgroundFetchResultFailed
}
分別表示獲取到了新數據(此時系統將對現在的UI狀態截圖并更新App Switcher中你的應用的截屏),沒有新數據,以及獲取失敗。不過以上操作的前提是已經在Background Modes
里面勾選了Remote notifications
(推送喚醒)且推送的消息中包含content-available
字段。
- 是 iOS 10 新增的
UNUserNotificationCenterDelegate
代理方法,在 iOS 10的環境下,點擊通知欄都會調用這個方法。 - 也是 iOS 10 新增的
UNUserNotificationCenterDelegate
代理方法,在iOS 10 以前,如果應用處于前臺狀態,接收到推送,通知欄是不會又任何提示的,如果開發者需要展示通知,需要自己在 3 的方法中提取通知內容展示。在iOS 10中如果開發者需要前臺展示通知,可以再在這個方法中completionHandler
傳入相應的參數。
typedef NS_OPTIONS(NSUInteger, UNNotificationPresentationOptions) {
UNNotificationPresentationOptionBadge = (1 << 0),
UNNotificationPresentationOptionSound = (1 << 1),
UNNotificationPresentationOptionAlert = (1 << 2),
}
總結:(最低系統環境為iOS 7)
- 當程序處于關閉狀態的時候收到推送消息,點擊應用程序圖標無法獲取推送消息, iOS 10 環境下,點擊通知欄會調用 方法1與4。非iOS 10的情況下,會調用方法1與3。
- 當程序處于前臺狀態下收到推送消息,iOS 10的環境下如果推送的消息中包含
content-available
字段的話執行方法3與4,否則只執行4。非iOS 10的情況下會執行方法3。 - 當程序處于后臺收到推送消息,如果已經在
Background Modes
里面勾選了Remote notifications
(推送喚醒)且推送的消息中包含content-available
字段的話,都會執行方法3。點擊通知欄 iOS 10會執行方法4,非iOS10會執行方法3。