iOS应用极光推送接收通知并打开指定功能界面

一、首先在iOS项目中嵌入极光推送的SDK,具体方法参照极光推送官网,里面涉及一些证书相关的东西,比安卓略显复杂
二、在应用的AppDelegate.m类中,初始化极光推送的sdk,实现接收消息的方法。



#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // ========================================================================
    // 顶部状态栏白色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    // ========================================================================
    //
    [DBManager initialDatabases];
    // ========================================================================
    // 百度地图API
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件,请设定     generalDelegate参数
    BOOL ret = [_mapManager start:@"2trUTYe3lbEO527FESyQRwKN"  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    // Add the navigation controller's view to the window and display.
    [self.window addSubview:navigationController.view];
    [self.window makeKeyAndVisible];
    // 百度地图结束
    // ========================================================================

    // 极光推送API。此处初始化极光推送的SDK
    // Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    // Required
    //如需兼容旧版本的方式,请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化和同时使用pushConfig.plist文件声明appKey等配置内容。
    [JPUSHService setupWithOption:launchOptions appKey:jPushAppKey channel:jPushChannel apsForProduction:isProduction];
    
    // ========================================================================
    
    
    return YES;
}


//- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
//{
//    return UIInterfaceOrientationMaskPortrait;
//}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


// =============================JPush 监听方法======================================================================
/* 
 // 官方建议开发者加上API里面提供下面 5 种类型的通知:
 extern NSString * const kJPFNetworkDidSetupNotification; // 建立连接
 
 extern NSString * const kJPFNetworkDidCloseNotification; // 关闭连接
 
 extern NSString * const kJPFNetworkDidRegisterNotification; // 注册成功
 
 extern NSString * const kJPFNetworkDidLoginNotification; // 登录成功
 */

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"=======");
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings: (UIUserNotificationSettings *)notificationSettings {
    NSLog(@"bbb");
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *) notification completionHandler:(void (^)())completionHandler {
    NSLog(@"ccccc");
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *) identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler {
    NSLog(@"aaaaa");
}
#endif

// 以下两个方法为接收极光消息的方法,useInfo为接收到的消息,可以打印到控制台看一下。将接收到的消息放到通知中心。
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *) userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"*********");
    NSLog(@"收到通知:%@", [self logDic:userInfo]);
   
    NSNotification *notification = [[NSNotification alloc] initWithName:kJPFNetworkDidReceiveMessageNotification object:nil userInfo:userInfo];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
   
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler: (void (^)(UIBackgroundFetchResult)) completionHandler {
    
    [JPUSHService handleRemoteNotification: userInfo];
    
   
    NSNotification *notification = [[NSNotification alloc] initWithName:kJPFNetworkDidReceiveMessageNotification object:nil userInfo:userInfo];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
   
    NSLog(@"………………………………");
    NSLog(@"收到通知:%@", [self logDic:userInfo]);
    
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    NSLog(@"xxxx");
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}

// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *) logDic:(NSDictionary *) dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}

@end



三、在根视图(我的项目的根视图是TabBarViewController)注册消息通知,成为上面指定消息的观察者

#import <Foundation/Foundation.h>
#import "DWKxbTabBarController.h"

@implementation DWKxbTabBarController

-(void) viewDidLoad{
    [super viewDidLoad];
    self.selectedIndex = 1;
    
   
    // 注册消息通知
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
 
}

// 具体的消息处理方法,比如我这里跳转到另外一个ViewController。
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSLog(@"tabxxxxxxxxxxxx");
    NSDictionary * userInfo = [notification userInfo];
    
    NSLog(@"%@", userInfo);
    
    self.selectedIndex = 1;
    
// 获取tabBar的当前选择视图
    DWLifeNavigationController *life = self.selectedViewController;
    // rootViewController
// 获取NavigationController的根视图(索引为0的child) 
    
    DWColorfulLifeViewController *root = life.childViewControllers[0];
    root.webViewParam = @"foods";
// 根据在storyboard中的连线跳转到指定的ViewController
    [root performSegueWithIdentifier:@"go2SpecialService" sender:root];
}

@end


PS: 第一次做这种功能,mark下来。文章代码里的颜色和粗体不起作用,好桑心

猜你喜欢

转载自jackeysion.iteye.com/blog/2281661
今日推荐