ios10推送案例

1.如下是我項目中的關於適配ios10推送更新的代碼,能夠直接用,因爲只是做爲我的之後的備忘錄,就直接拷貝過來,如有網友看到有不清楚的地方,儘可留言ios

#import "AppDelegate.h"

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate (XPush) <UNUserNotificationCenterDelegate>

@property (nonatomic, copy) NSString *token;

@end
//
//  AppDelegate+XPush.m
//  myFirstApp
//
//  Created by qifanrui on 16/6/27.
//
//

#import "AppDelegate+XPush.h"
#import <objc/runtime.h>

#ifndef __OPTIMIZE__
#define NSLog(...) NSLog(__VA_ARGS__)
#else
#define NSLog(...) {}
#endif

@implementation AppDelegate (XPush)

static char tokenKey;

- (NSString *)token
{
    return objc_getAssociatedObject(self, &tokenKey);
}
- (void)setToken:(NSString *)token
{
    objc_setAssociatedObject(self, &tokenKey, token, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
//當app在後臺運行時,激活APP時會走這個方法,在這裏面裏能夠對推送消息作響應的處理
-(void)applicationDidBecomeActive:(UIApplication *)application{
    //把icon上的標記數字設置爲0,
    application.applicationIconBadgeNumber = 0;
//Cancel all remote notifications取消全部遠程通知
    [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
}
- (id)init
{
    /** If you need to do any extra app-specific initialization, you can do it here
     *  -jm
     **/
    NSHTTPCookieStorage* cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    
    int cacheSizeMemory = 8 * 1024 * 1024; // 8MB
    int cacheSizeDisk = 32 * 1024 * 1024; // 32MB
#if __has_feature(objc_arc)
    NSURLCache* sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
#else
    NSURLCache* sharedCache = [[[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"] autorelease];
#endif
    [NSURLCache setSharedURLCache:sharedCache];
    self = [super init];
    //註冊消息推送
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        //iOS10特有
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        // 必須寫代理,否則沒法監聽通知的接收與點擊
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                // 點擊容許
                NSLog(@"註冊成功");
                [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                    NSLog(@"%@", settings);
                }];
            } else {
                // 點擊不容許
                NSLog(@"註冊失敗");
            }
        }];
    }else if ([[UIDevice currentDevice].systemVersion floatValue] >=8.0){
        //iOS8 - iOS10
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge categories:nil]];
        
    }else if ([[UIDevice currentDevice].systemVersion floatValue] < 8.0) {
        //iOS8系統如下
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
    }
    // 註冊得到device Token
    [[UIApplication sharedApplication] registerForRemoteNotifications];

    return self;
}

//獲取DeviceToken成功
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken NS_AVAILABLE_IOS(3_0){
    NSString *deviceTokenSt = [[[[deviceToken description]
                                 stringByReplacingOccurrencesOfString:@"<" withString:@""]
                                stringByReplacingOccurrencesOfString:@">" withString:@""]
                               stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"deviceTokenSt:%@",deviceTokenSt);
    self.token = deviceTokenSt;
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error NS_AVAILABLE_IOS(3_0){
    NSLog(@"didFailToRegisterForRemoteNotificationsWithError:%@",error);
}
//處理收到的消息推送
#ifdef __IPHONE_10_0
#pragma mark  iOS 10 獲取推送信息 UNUserNotificationCenterDelegate
//App在前臺的時候收到推送執行的回調方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    UNNotificationContent *content =  notification.request.content;
    NSDictionary *userInfo = content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"iOS10 前臺收到遠程通知");
        NSLog(@"notification========%@", notification);
        [self handleRemoteNotificationContent:userInfo];
        //能夠執行設置 彈窗 和 聲音
        completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound);// 須要執行這個方法,選擇是否提醒用戶,有Badge、Sound、Alert三種類型能夠設置
//        UIAlertView *alr = [[UIAlertView alloc]initWithTitle:@"前臺收到遠程推送" message:notification.request.content.body delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"肯定", nil];
//        [alr show];
//展現後再取消這個通知
        [center removeDeliveredNotificationsWithIdentifiers:@[notification.request.identifier]];
    }
    else {
        // 判斷爲本地通知
        NSLog(@"iOS10 前臺收到本地通知");
    }
    // 這裏真實須要處理交互的地方
    // 獲取通知所帶的數據
//    NSString *notMess = [notification.request.content.userInfo objectForKey:@"aps"];
//    NSLog(@"notMess========%@", notMess);
//    NSLog(@"willPresentNotification:%@",notification.request.content.body);
}
//App在後臺的時候,點擊推送信息,進入App後執行的 回調方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    UNNotificationContent *content  = response.notification.request.content;
    NSDictionary *userInfo = content.userInfo;
    //在沒有啓動本App時,收到服務器推送消息,下拉消息會有快捷回覆的按鈕,點擊按鈕後調用的方法,根據identifier來判斷點擊的哪一個按鈕
    NSString *notMess = [response.notification.request.content.userInfo objectForKey:@"aps"];
    NSLog(@"notMess:%@", notMess);
    NSString *categoryIdentifier = response.notification.request.content.categoryIdentifier;
    if ([categoryIdentifier isEqualToString:@"handle category"]) {//識別須要被處理的拓展
        
        if ([response.actionIdentifier isEqualToString:@"input text"]) {//識別用戶點擊的是哪一個 action
            //假設點擊了輸入內容的 UNTextInputNotificationAction 把 response 強轉類型
            UNTextInputNotificationResponse *textResponse = (UNTextInputNotificationResponse*)response;
            //獲取輸入內容
            NSString *userText = textResponse.userText;
            //發送 userText 給須要接收的方法
            NSLog(@"userText:%@", userText);
//            [ClassName handleUserText: userText];
        }else{
            
        }
        
    }
//    NSLog(@"didReceiveNotificationResponse:%@",response.notification.request.content.title);
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"iOS10 後臺收到遠程通知");
        NSLog(@"response:%@", response);
        //點擊通知進入應用
        [self handleRemoteNotificationContent:userInfo];
        UIAlertView *alr = [[UIAlertView alloc]initWithTitle:@"點擊通知進入應用" message:response.notification.request.content.body delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"肯定", nil];
        [alr show];
    }
    else {
        // 判斷爲本地通知
        NSLog(@"iOS10 後臺收到本地通知");
    }
    completionHandler();// 系統要求執行這個方法
}
- (void)handleRemoteNotificationContent:(NSDictionary *)userInfo
{
    NSLog(@" iOS 10 after Notificatoin message:\n %@",userInfo);
//    UIAlertView *alr = [[UIAlertView alloc]initWithTitle:@"我進來了" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"肯定", nil];
//    [alr show];
}
#else
//遠程推送APP收到
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    NSLog(@"didReceiveRemoteNotification:%@",userInfo);
//    UIAlertView *alr = [[UIAlertView alloc]initWithTitle:@"點我了" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"肯定", nil];
//    [alr show];
    
}
#endif
@end
相關文章
相關標籤/搜索