iOS10全新推送功能實現代碼_IOS

來源:互聯網
上載者:User

從iOS8.0開始推送功能的實現在不斷改變,功能也在不斷增加,iOS10又出來了一個推送外掛程式的開發(見最後圖),廢話不多說直接上代碼: 

#import <UserNotifications/UserNotifications.h> - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch.  /* APP未啟動,點擊推送訊息的情況下 iOS10遺棄UIApplicationLaunchOptionsLocalNotificationKey,使用代理UNUserNotificationCenterDelegate方法didReceiveNotificationResponse:withCompletionHandler:擷取本地推送 */// NSDictionary *localUserInfo = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];// if (localUserInfo) {// NSLog(@"localUserInfo:%@",localUserInfo);// //APP未啟動,點擊推送訊息// } NSDictionary *remoteUserInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]; if (remoteUserInfo) { NSLog(@"remoteUserInfo:%@",remoteUserInfo); //APP未啟動,點擊推送訊息,iOS10下還是跟以前一樣在此擷取 } [self registerNotification]; return YES;}
 

註冊推送方法的改變:

新增庫 #import <UserNotifications/UserNotifications.h>  推送單列UNUserNotificationCenter 等API 

- (void)registerNotification{ /* identifier:行為標識符,用於調用代理方法時識別是哪種行為。 title:行為名稱。 UIUserNotificationActivationMode:即行為是否開啟APP。 authenticationRequired:是否需要解鎖。 destructive:這個決定按鈕顯示顏色,YES的話按鈕會是紅色。 behavior:點擊按鈕文字輸入,是否彈出鍵盤 */ UNNotificationAction *action1 = [UNNotificationAction actionWithIdentifier:@"action1" title:@"策略1行為1" options:UNNotificationActionOptionForeground]; /*iOS9實現方法 UIMutableUserNotificationAction * action1 = [[UIMutableUserNotificationAction alloc] init]; action1.identifier = @"action1"; action1.title=@"策略1行為1"; action1.activationMode = UIUserNotificationActivationModeForeground; action1.destructive = YES; */  UNTextInputNotificationAction *action2 = [UNTextInputNotificationAction actionWithIdentifier:@"action2" title:@"策略1行為2" options:UNNotificationActionOptionDestructive textInputButtonTitle:@"textInputButtonTitle" textInputPlaceholder:@"textInputPlaceholder"]; /*iOS9實現方法 UIMutableUserNotificationAction * action2 = [[UIMutableUserNotificationAction alloc] init]; action2.identifier = @"action2"; action2.title=@"策略1行為2"; action2.activationMode = UIUserNotificationActivationModeBackground; action2.authenticationRequired = NO; action2.destructive = NO; action2.behavior = UIUserNotificationActionBehaviorTextInput;//點擊按鈕文字輸入,是否彈出鍵盤 */  UNNotificationCategory *category1 = [UNNotificationCategory categoryWithIdentifier:@"Category1" actions:@[action2,action1] minimalActions:@[action2,action1] intentIdentifiers:@[@"action1",@"action2"] options:UNNotificationCategoryOptionCustomDismissAction]; // UIMutableUserNotificationCategory * category1 = [[UIMutableUserNotificationCategory alloc] init]; // category1.identifier = @"Category1"; // [category1 setActions:@[action2,action1] forContext:(UIUserNotificationActionContextDefault)];  UNNotificationAction *action3 = [UNNotificationAction actionWithIdentifier:@"action3" title:@"策略2行為1" options:UNNotificationActionOptionForeground]; // UIMutableUserNotificationAction * action3 = [[UIMutableUserNotificationAction alloc] init]; // action3.identifier = @"action3"; // action3.title=@"策略2行為1"; // action3.activationMode = UIUserNotificationActivationModeForeground; // action3.destructive = YES;  UNNotificationAction *action4 = [UNNotificationAction actionWithIdentifier:@"action4" title:@"策略2行為2" options:UNNotificationActionOptionForeground]; // UIMutableUserNotificationAction * action4 = [[UIMutableUserNotificationAction alloc] init]; // action4.identifier = @"action4"; // action4.title=@"策略2行為2"; // action4.activationMode = UIUserNotificationActivationModeBackground; // action4.authenticationRequired = NO; // action4.destructive = NO;  UNNotificationCategory *category2 = [UNNotificationCategory categoryWithIdentifier:@"Category2" actions:@[action3,action4] minimalActions:@[action3,action4] intentIdentifiers:@[@"action3",@"action4"] options:UNNotificationCategoryOptionCustomDismissAction]; // UIMutableUserNotificationCategory * category2 = [[UIMutableUserNotificationCategory alloc] init]; // category2.identifier = @"Category2"; // [category2 setActions:@[action4,action3] forContext:(UIUserNotificationActionContextDefault)];   [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:category1,category2, nil]]; [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) { NSLog(@"completionHandler"); }]; /*iOS9實現方法 UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:[NSSet setWithObjects: category1,category2, nil]]; [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; */ [[UIApplication sharedApplication] registerForRemoteNotifications];   [UNUserNotificationCenter currentNotificationCenter].delegate = self;}

代理方法的改變:

 一些本地和遠程推送的回調放在了同一個代理方法

#pragma mark -- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings NS_AVAILABLE_IOS(8_0) __TVOS_PROHIBITED{ NSLog(@"didRegisterUserNotificationSettings");}- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken NS_AVAILABLE_IOS(3_0){ NSLog(@"deviceToken:%@",deviceToken); NSString *deviceTokenSt = [[[[deviceToken description]   stringByReplacingOccurrencesOfString:@"<" withString:@""]  stringByReplacingOccurrencesOfString:@">" withString:@""]  stringByReplacingOccurrencesOfString:@" " withString:@""]; NSLog(@"deviceTokenSt:%@",deviceTokenSt);}- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error NS_AVAILABLE_IOS(3_0){ NSLog(@"didFailToRegisterForRemoteNotificationsWithError:%@",error);}/*iOS9使用方法- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo NS_DEPRECATED_IOS(3_0, 10_0, "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:] or -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:] for user visible notifications and -[UIApplicationDelegate application:didReceiveRemoteNotification:fetchCompletionHandler:] for silent remote notifications"){ }*/- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{ NSLog(@"willPresentNotification:%@",notification.request.content.title);  // 這裡真實需要處理互動的地方 // 擷取通知所帶的資料 NSString *notMess = [notification.request.content.userInfo objectForKey:@"aps"]; }- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{ //在沒有啟動本App時,收到伺服器推送訊息,下拉訊息會有快捷回複的按鈕,點擊按鈕後調用的方法,根據identifier來判斷點擊的哪個按鈕 NSString *notMess = [response.notification.request.content.userInfo objectForKey:@"aps"]; NSLog(@"didReceiveNotificationResponse:%@",response.notification.request.content.title);// response.notification.request.identifier}//遠程推送APP在前台- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{ NSLog(@"didReceiveRemoteNotification:%@",userInfo);}/*- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler NS_DEPRECATED_IOS(8_0, 10_0, "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:]") __TVOS_PROHIBITED{ }*//*// 本地通知回呼函數,當應用程式在前台時調用- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification NS_DEPRECATED_IOS(4_0, 10_0, "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:] or -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:]") __TVOS_PROHIBITED{ NSLog(@"didReceiveLocalNotification:%@",notification.userInfo);   // 這裡真實需要處理互動的地方 // 擷取通知所帶的資料 NSString *notMess = [notification.userInfo objectForKey:@"aps"]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"本地通知(前台)"    message:notMess    delegate:nil   cancelButtonTitle:@"OK"   otherButtonTitles:nil]; [alert show];  // 更新顯示的徽章個數 NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber; badge--; badge = badge >= 0 ? badge : 0; [UIApplication sharedApplication].applicationIconBadgeNumber = badge;  // 在不需要再推送時,可以取消推送 [FirstViewController cancelLocalNotificationWithKey:@"key"];}- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler NS_DEPRECATED_IOS(8_0, 10_0, "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:]") __TVOS_PROHIBITED{ //在非本App介面時收到本地訊息,下拉訊息會有快捷回複的按鈕,點擊按鈕後調用的方法,根據identifier來判斷點擊的哪個按鈕,notification為訊息內容 NSLog(@"%@----%@",identifier,notification); completionHandler();//處理完訊息,最後一定要調用這個代碼塊}*/

 還有推送外掛程式開發: 類似iOS tody widget外掛程式開發

 

本文已被整理到了《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.