iOS app Jiguang push to receive notifications and open the specified function interface

1. First, embed the SDK of Jiguang Push in the iOS project. For the specific method, refer to the official website of Jiguang Push, which involves some certificate-related things, which is slightly more complicated than Android.
Second , in the AppDelegate.m class of the application, initialize the SDK of Jiguang Push, Implement the method to receive the message.



#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // ========================================================================
    // top status bar white
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    // ========================================================================
    //
    [DBManager initialDatabases];
    // ========================================================================
    // Baidu Map API
    _mapManager = [[BMKMapManager alloc]init];
    // If you want to pay attention to network and authorization verification events, please set the generalDelegate parameter
    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];
    // end of Baidu map
    // ========================================================================

    // Aurora push API. Initialize the SDK pushed by Jiguang here
    // Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //You can add custom categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories must be nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    // Required
    //If you need to be compatible with the old version, please still use the [JPUSHService setupWithOption:launchOptions] method to initialize and use the pushConfig.plist file to declare configuration content such as 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 monitoring method================== ===================================================== ====
/*
 // Officially recommend that developers add the following 5 types of notifications in the API:
 extern NSString * const kJPFNetworkDidSetupNotification; // establish connection
 
 extern NSString * const kJPFNetworkDidCloseNotification; // close the connection
 
 extern NSString * const kJPFNetworkDidRegisterNotification; // successful registration
 
 extern NSString * const kJPFNetworkDidLoginNotification; // Login successful
 */

- (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

// The following two methods are methods for receiving Jiguang messages, and useInfo is the received message, which can be printed to the console to see. Put the received message in the notification center.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *) userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"*********");
    NSLog(@"Notification received:%@", [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(@"Notification received:%@", [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



3. Register the message notification in the root view (the root view of my project is TabBarViewController) and become the observer of the message specified above

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

@implementation DWKxbTabBarController

-(void) viewDidLoad{
    [super viewDidLoad];
    self.selectedIndex = 1;
    
   
    // register for notification
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
 
}

// The specific message processing method, for example, I jump to another ViewController here.
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSLog(@"tabxxxxxxxxxxxx");
    NSDictionary * userInfo = [notification userInfo];
    
    NSLog(@"%@", userInfo);
    
    self.selectedIndex = 1;
    
// Get the currently selected view of the tabBar
    DWLifeNavigationController *life = self.selectedViewController;
    // rootViewController
// Get the root view of NavigationController (child with index 0)
    
    DWColorfulLifeViewController *root = life.childViewControllers[0];
    root.webViewParam = @"foods";
// Jump to the specified ViewController based on the connection in the storyboard
    [root performSegueWithIdentifier:@"go2SpecialService" sender:root];
}

@end


PS: This is the first time to do this function, mark it down. The color and bold in the article code don't work, so sad

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326966635&siteId=291194637