Parse.com Push通知[SwiftおよびObjective-C、Objective-C++(cocos2dx)]

本文では主にカスタム通知を取り扱いします。
またPasre serverの立ち上げやp12ファイルの取得のしかたなどは割愛します。

swift ver

 //  AppDelegate.swift
 //
 //  Copyright (c) 2020年 SHOGO SATO. All rights reserved.
 //
 import UIKit
 import Parse
 import UserNotifications
 
 @UIApplicationMain
 class AppDelegate: UIResponder, UIApplicationDelegate,{
 
var window: UIWindow?

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        
 print("PARSE_VERSION",PARSE_VERSION)

        

        

        //バッジを消す

        UIApplication.shared.applicationIconBadgeNumber = 0

        

        

        


        let configuration = ParseClientConfiguration {

            $0.applicationId = "XXXXX"

            $0.clientKey = "XXXXX"

            $0.server = "https://XXXXX/parse"

        }

        Parse.initialize(with: configuration)

        

        

        if application.applicationState != UIApplication.State.background {

            // Track an app open here if we launch with a push, unless

            // "content_available" was used to trigger a background push (introduced in iOS 7).

            // In that case, we skip tracking here to avoid double counting the app-open.

            

            let preBackgroundPush = !application.responds(to: #selector(getter: UIApplication.backgroundRefreshStatus))

            

            let oldPushHandlerOnly = !self.responds(to: #selector(UIApplicationDelegate.application(_:didReceiveRemoteNotification:fetchCompletionHandler:)))

            

            var noPushPayload = false;

            

            if let options = launchOptions {

                noPushPayload = options[UIApplication.LaunchOptionsKey.remoteNotification] != nil;

            }

            

            if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) {

                PFAnalytics.trackAppOpened(launchOptions: launchOptions)

            }

        }

        

        

        

        if #available(iOS 8.0, *) {

            let types: UIUserNotificationType = [.alert, .badge, .sound]

            let settings = UIUserNotificationSettings(types: types, categories: nil)

            application.registerUserNotificationSettings(settings)

            application.registerForRemoteNotifications()

            

        } else {

            

            let types: UIRemoteNotificationType = [.alert, .badge, .sound]

            application.registerForRemoteNotifications(matching: types)

        }

        

        

        // self.window?.makeKeyAndVisible()

        

        

        return true

    }

    

    // Called when the application is about to terminate.

    func applicationWillTerminate(_ application: UIApplication) {

        // Remove the observer.

        
    }

    

    func applicationDidBecomeActive(_ application: UIApplication) {

        // 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.

        

        print("applicationDidBecomeActive")

        
    }

    

    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {

        

        return ApplicationDelegate.shared.application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)

    }

    

    

    

    

    //--------------------------------------

    // MARK: Push Notifications

    //--------------------------------------

    

    //デバイストークン

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        let token = deviceToken.map { String(format: "%.2hhx", $0) }.joined()

        print("token",token)

        

        let currentInstallation: PFInstallation = PFInstallation.current()!

        currentInstallation.channels = ["XXXXX"]

        currentInstallation.setDeviceTokenFrom(deviceToken)

        currentInstallation.saveInBackground()

        PFPush.subscribeToChannel(inBackground: "") { (succeeded: Bool, error: Error?) in

            if succeeded {

                

                print("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.\n");

                

            } else {

                

                print("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %@.\n", error!)

            }

        }

    }

    

    

    

    

    // Push通知が利用不可であればerrorが返ってくる

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {

        NSLog("error: " + "\(error)")

    }

    

    @available(iOS 8.0, *)

    func application(_ application: UIApplication, didRegister notificationSettings:UIUserNotificationSettings) {

        application.registerForRemoteNotifications()

    }

  
    //RemotePush通知取得関数

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void){

        // application.applicationStateを調べるとフォアグラウンドかバックグランドの判別ができます

        

        print("didReceiveRemoteNotification",userInfo);

       
        //userInfoにはサーバー側で記述した"apns_payload"が格納されている

        if let customData = userInfo["aps" as NSString] as? NSDictionary {

            //if let customData = userInfo["aps" as NSString] as? [[String: AnyObject]] {

            

            let alertView = UIAlertView()

            //alertView.title = customData["alert"] as! NSString as String+""+"\(Language.sharedInstance.increPoint)"

            alertView.title = customData["alert"] as! NSString as String

            let urlLink: String = customData["url"] as! NSString as String

            let url: NSURL = NSURL(string: urlLink)!

            NSLog("About to Open Safari")

            if !UIApplication.shared.openURL(url as URL) {

                NSLog("Failed to open url:%@", url.description)

            }

            

            alertView.cancelButtonIndex = 1

            alertView.delegate = self

            alertView.show()

        }

        completionHandler(.noData)

        if (userInfo["job_id" as NSString] != nil) {

            let jobID = userInfo["job_id" as NSString]as! Int

            print("\(jobID)")

        }

        

        //Storage.sharedInstance.pushBounus()

        print("fetchCompletionHandler")

        

    }

    

    

    //アプリケーションが起動している状態もしくは通知から起動した場合に呼ばれる

    

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {

        

        

        //        let aps = userInfo["aps" as NSString] as? [String:AnyObject]

        //        let alert = aps?["alert"] as? [String:AnyObject]

        //        let title = alert?["title"] as? String

        //        let body = alert?["body"] as? String

        

        

        

        

        

        //userInfoにはサーバー側で記述した"apns_payload"が格納されている

        if let customData = userInfo["aps" as NSString] as? NSDictionary {

            

            let alertView = UIAlertView()

            //alertView.title = customData["alert"] as! NSString as String+""+"\(Language.sharedInstance.increPoint)"

            alertView.title = customData["alert"] as! NSString as String

            let urlLink: String = customData["url"] as! NSString as String

            let url: NSURL = NSURL(string: urlLink)!

            NSLog("About to Open Safari")

            if !UIApplication.shared.openURL(url as URL) {

                NSLog("Failed to open url:%@", url.description)

            }

            

            alertView.cancelButtonIndex = 1

            alertView.delegate = self

            alertView.show()

        }

        //completionHandler(.noData)

        if (userInfo["job_id" as NSString] != nil) {

            let jobID = userInfo["job_id" as NSString]as! Int

            print("\(jobID)")

        }

        
        print("application:didReceiveRemoteNotification: " + userInfo.description);

    }

}
    





Objective-C Ver

#import "AppDelegate.h"

#import <Parse/Parse.h>
@interface AppDelegate(){


}

@end

 

@implementation AppDelegate

 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    

    NSLog(@"didFinishLaunchingWithOptions--IOS");

    [UIApplication sharedApplication].applicationIconBadgeNumber = -1;

    

    [Parse initializeWithConfiguration:[ParseClientConfiguration configurationWithBlock:^(id<ParseMutableClientConfiguration> configuration) {

        configuration.applicationId = @"XXXXX";

        configuration.clientKey = @"XXXXX";

        configuration.server = @"https://XXXXX/parse";

    }]];

    

    if (application.applicationState != UIApplicationStateBackground) {

        // Track an app open here if we launch with a push, unless

        // "content_available" was used to trigger a background push (introduced

        // in iOS 7). In that case, we skip tracking here to avoid double

        // counting the app-open.

        BOOL preBackgroundPush = ![application respondsToSelector:@selector(backgroundRefreshStatus)];

        BOOL oldPushHandlerOnly = ![self respondsToSelector:@selector(application:didReceiveRemoteNotification:fetchCompletionHandler:)];

        BOOL noPushPayload = ![launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

        if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) {

            [PFAnalytics trackAppOpenedWithLaunchOptions:launchOptions];

        }

    }

    

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

    {

        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];

        [[UIApplication sharedApplication] registerForRemoteNotifications];

        NSLog(@"ios8");

    }

    else

    {

        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:

         (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];

        

        NSLog(@"ios7");

    }

    
    

    return YES;

}

 

 

//以下追加

- (void)application:(UIApplication *)application

didReceiveRemoteNotification:(NSDictionary *)userInfo

fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

{

    NSLog(@"fetchCompletionHandler");

    

    

    NSDictionary *aps = (NSDictionary *)[userInfo objectForKey:@"aps"];

    NSMutableString *alert = [NSMutableString stringWithString:@""];

    if ([aps objectForKey:@"alert"])

    {

        [alert appendString:(NSString *)[aps objectForKey:@"alert"]];

    }

    

    if (aps !=nil && [aps objectForKey:@"url"] !=[NSNull null] &&

        [[aps objectForKey:@"url"] length] > 0 ) {

        

        NSLog(@"About to Open Safari");

        // NSString *urlLink=[[NSString alloc]initWithString:[aps objectForKey:@"url"]];

        NSString *urlLink=[NSString stringWithFormat:

                           @"%@",[aps objectForKey:@"url"]];

        NSURL *url = [NSURL URLWithString:urlLink];

        

        if (![[UIApplication sharedApplication] openURL:url]) {

            NSLog(@"Failed to open url:%@",[url description]);

        }

    }

    

    if ([userInfo objectForKey:@"job_id"])

    {

        // do something with job id

        int jobID = [[userInfo objectForKey:@"job_id"] intValue];

        NSLog(@"int jobID");

    }

    

    

}

 

 

//デバイストークン

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    //インストール

    PFInstallation *currentInstallation = [PFInstallation currentInstallation];

    

    // デバイストークンの両端の「<>」を取り除く

    NSString *deviceTokenString = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];

    

    // デバイストークン中の半角スペースを除去する

    deviceTokenString = [deviceTokenString stringByReplacingOccurrencesOfString:@" " withString:@""];

    

    //デバイストークン

    [currentInstallation setDeviceTokenFromData:deviceToken];

    

    

    

    //チャンネル

    currentInstallation.channels = @[@"林檎嫌い"];

    //セーブ

    [currentInstallation saveInBackground];

    

    

    NSLog(@"%@",deviceTokenString);

    //  NSLog(@"%@",deviceToken);

}

 

 

//エラーコード

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

    if (error.code == 3010) {

        NSLog(@"Push notifications are not supported in the iOS Simulator.");

    } else {

        // show some alert or otherwise handle the failure to register.

        NSLog(@"application:didFailToRegisterForRemoteNotificationsWithError: %@", error);

    }

}

 

 

//json形式でpush通知を送る

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification {

    [PFPush handlePush:notification];

    

    NSLog(@"didReceiveRemoteNotification");

    

    NSDictionary *aps = (NSDictionary *)[notification objectForKey:@"aps"];

    NSMutableString *alert = [NSMutableString stringWithString:@""];

    if ([aps objectForKey:@"alert"])

    {

        [alert appendString:(NSString *)[aps objectForKey:@"alert"]];

    }

    

    if (aps !=nil && [aps objectForKey:@"url"] !=[NSNull null] &&

        [[aps objectForKey:@"url"] length] > 0 ) {

        

        NSLog(@"About to Open Safari");

        // NSString *urlLink=[[NSString alloc]initWithString:[aps objectForKey:@"url"]];

        NSString *urlLink=[NSString stringWithFormat:

                           @"%@",[aps objectForKey:@"url"]];

        NSURL *url = [NSURL URLWithString:urlLink];

        

        if (![[UIApplication sharedApplication] openURL:url]) {

            NSLog(@"Failed to open url:%@",[url description]);

        }

    }

    

    if ([notification objectForKey:@"job_id"])

    {

        // do something with job id

        int jobID = [[notification objectForKey:@"job_id"] intValue];

        NSLog(@"int jobID");

    }

    

}

 

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings

{

    [application registerForRemoteNotifications];

}

 

 

//ハンドラー

- (void)handleBackgroundNotification:(NSDictionary *)notification

{

    NSDictionary *aps = (NSDictionary *)[notification objectForKey:@"aps"];

    NSMutableString *alert = [NSMutableString stringWithString:@""];

    if ([aps objectForKey:@"alert"])

    {

        [alert appendString:(NSString *)[aps objectForKey:@"alert"]];

    }

    

    if (aps !=nil && [aps objectForKey:@"url"] !=[NSNull null] &&

        [[aps objectForKey:@"url"] length] > 0 ) {

        NSLog(@"About to Open Safari");

        // NSString *urlLink=[[NSString alloc]initWithString:[aps objectForKey:@"url"]];

        NSString *urlLink=[NSString stringWithFormat:

                           @"%@",[aps objectForKey:@"url"]];

        NSURL *url = [NSURL URLWithString:urlLink];

        if (![[UIApplication sharedApplication] openURL:url]) {

            NSLog(@"Failed to open url:%@",[url description]);

        }

    }

    

    if ([notification objectForKey:@"job_id"])

    {

        // do something with job id

        int jobID = [[notification objectForKey:@"job_id"] intValue];

        NSLog(@"int jobID");

    }

    

}



@end




Objective-C++(cocos2dx) Ver

#import <UIKit/UIKit.h>

#import "cocos2d.h"

#import "AppController.h"

#import "AppDelegate.h"

#import "RootViewController.h"

#import "platform/ios/CCEAGLView-ios.h"

//追加
#import <Parse/Parse.h>

@implementation AppController

 

#pragma mark -

#pragma mark Application lifecycle

 

// cocos2d application instance

static AppDelegate s_sharedApplication;

 


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    

    NSLog(@"didFinishLaunchingWithOptions--IOS");

  

    [Parse initializeWithConfiguration:[ParseClientConfiguration configurationWithBlock:^(id<ParseMutableClientConfiguration> configuration) {

        configuration.applicationId = @"XXXXXX";

        configuration.clientKey = @"XXXXXX";

        configuration.server = @"https:XXXXX/parse";

    }]];

    

    if (application.applicationState != UIApplicationStateBackground) {

        // Track an app open here if we launch with a push, unless

        // "content_available" was used to trigger a background push (introduced

        // in iOS 7). In that case, we skip tracking here to avoid double

        // counting the app-open.

        BOOL preBackgroundPush = ![application respondsToSelector:@selector(backgroundRefreshStatus)];

        BOOL oldPushHandlerOnly = ![self respondsToSelector:@selector(application:didReceiveRemoteNotification:fetchCompletionHandler:)];

        BOOL noPushPayload = ![launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

        if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) {

            [PFAnalytics trackAppOpenedWithLaunchOptions:launchOptions];

        }

    }

    

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

    {

        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];

        [[UIApplication sharedApplication] registerForRemoteNotifications];

        NSLog(@"ios8");

    }

    else

    {

        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:

         (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];

        

        NSLog(@"ios7");

    }

    

    

    // Override point for customization after application launch.

    

    // Add the view controller's view to the window and display.

    window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];

    CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [window bounds]

                                         pixelFormat: kEAGLColorFormatRGBA8

                                         depthFormat: GL_DEPTH24_STENCIL8_OES

                                  preserveBackbuffer: NO

                                          sharegroup: nil

                                       multiSampling: NO

                                     numberOfSamples: 0 ];

    

    [eaglView setMultipleTouchEnabled:YES];

    

    // Use RootViewController manage CCEAGLView

    viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];

    viewController.wantsFullScreenLayout = YES;

    viewController.view = eaglView;

    

    // Set RootViewController to window

    if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0)

    {

        // warning: addSubView doesn't work on iOS6

        [window addSubview: viewController.view];

    }

    else

    {

        // use this method on ios6

        [window setRootViewController:viewController];

    }

    

    [window makeKeyAndVisible];

    

    [[UIApplication sharedApplication] setStatusBarHidden: YES];

    

    // IMPORTANT: Setting the GLView should be done after creating the RootViewController

    cocos2d::GLView *glview = cocos2d::GLViewImpl::createWithEAGLView(eaglView);

    cocos2d::Director::getInstance()->setOpenGLView(glview);

    

    

    

    

    cocos2d::Application::getInstance()->run();

    

    

    

    

    

    return YES;

}

 

 

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

     */

    cocos2d::Director::getInstance()->pause();

}

 

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

     */

    cocos2d::Director::getInstance()->resume();

}

 

- (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, called instead of applicationWillTerminate: when the user quits.

     */

    cocos2d::Application::getInstance()->applicationDidEnterBackground();

}

 

- (void)applicationWillEnterForeground:(UIApplication *)application {

    /*

     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.

     */

    cocos2d::Application::getInstance()->applicationWillEnterForeground();

}

 

- (void)applicationWillTerminate:(UIApplication *)application {

    /*

     Called when the application is about to terminate.

     See also applicationDidEnterBackground:.

     */

}

 

 

#pragma mark -

#pragma mark Memory management

 

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {

    /*

     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.

     */

    cocos2d::Director::getInstance()->purgeCachedData();

}

 

 

- (void)dealloc {

    [super dealloc];

}

 

 

 

//以下追加

- (void)application:(UIApplication *)application

didReceiveRemoteNotification:(NSDictionary *)userInfo

fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

{

    NSLog(@"fetchCompletionHandler");

    

    

    NSDictionary *aps = (NSDictionary *)[userInfo objectForKey:@"aps"];

    NSMutableString *alert = [NSMutableString stringWithString:@""];

    if ([aps objectForKey:@"alert"])

    {

        [alert appendString:(NSString *)[aps objectForKey:@"alert"]];

    }

    

    if (aps !=nil && [aps objectForKey:@"url"] !=[NSNull null] &&

        [[aps objectForKey:@"url"] length] > 0 ) {

        

        NSLog(@"About to Open Safari");

        // NSString *urlLink=[[NSString alloc]initWithString:[aps objectForKey:@"url"]];

        NSString *urlLink=[NSString stringWithFormat:

                           @"%@",[aps objectForKey:@"url"]];

        NSURL *url = [NSURL URLWithString:urlLink];

        

        if (![[UIApplication sharedApplication] openURL:url]) {

            NSLog(@"Failed to open url:%@",[url description]);

        }

    }

    

    if ([userInfo objectForKey:@"job_id"])

    {

        // do something with job id

        int jobID = [[userInfo objectForKey:@"job_id"] intValue];

        NSLog(@"int jobID");

    }

    

    

}

 

 

 

 

//デバイストークン

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    //インストール

    PFInstallation *currentInstallation = [PFInstallation currentInstallation];

    

    // デバイストークンの両端の「<>」を取り除く

    NSString *deviceTokenString = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];

    

    // デバイストークン中の半角スペースを除去する

    deviceTokenString = [deviceTokenString stringByReplacingOccurrencesOfString:@" " withString:@""];

    

    //デバイストークン

    [currentInstallation setDeviceTokenFromData:deviceToken];

    

    

    

    //チャンネル

    currentInstallation.channels = @[@"林檎アホ"];

    //セーブ

    [currentInstallation saveInBackground];

    

    

    NSLog(@"%@",deviceTokenString);

    //  NSLog(@"%@",deviceToken);

}

 

 

//エラーコード

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

    if (error.code == 3010) {

        NSLog(@"Push notifications are not supported in the iOS Simulator.");

    } else {

        // show some alert or otherwise handle the failure to register.

        NSLog(@"application:didFailToRegisterForRemoteNotificationsWithError: %@", error);

    }

}

 

 

//json形式でpush通知を送る

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification {

    [PFPush handlePush:notification];

    

    NSLog(@"didReceiveRemoteNotification");

    

    NSDictionary *aps = (NSDictionary *)[notification objectForKey:@"aps"];

    NSMutableString *alert = [NSMutableString stringWithString:@""];

    if ([aps objectForKey:@"alert"])

    {

        [alert appendString:(NSString *)[aps objectForKey:@"alert"]];

    }

    

    if (aps !=nil && [aps objectForKey:@"url"] !=[NSNull null] &&

        [[aps objectForKey:@"url"] length] > 0 ) {

        

        NSLog(@"About to Open Safari");

        // NSString *urlLink=[[NSString alloc]initWithString:[aps objectForKey:@"url"]];

        NSString *urlLink=[NSString stringWithFormat:

                           @"%@",[aps objectForKey:@"url"]];

        NSURL *url = [NSURL URLWithString:urlLink];

        

        if (![[UIApplication sharedApplication] openURL:url]) {

            NSLog(@"Failed to open url:%@",[url description]);

        }

    }

    

    if ([notification objectForKey:@"job_id"])

    {

        // do something with job id

        int jobID = [[notification objectForKey:@"job_id"] intValue];

        NSLog(@"int jobID");

    }

    

}

 

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings

{

    [application registerForRemoteNotifications];

}

 

 

//ハンドラー

- (void)handleBackgroundNotification:(NSDictionary *)notification

{

    NSDictionary *aps = (NSDictionary *)[notification objectForKey:@"aps"];

    NSMutableString *alert = [NSMutableString stringWithString:@""];

    if ([aps objectForKey:@"alert"])

    {

        [alert appendString:(NSString *)[aps objectForKey:@"alert"]];

    }

    

    if (aps !=nil && [aps objectForKey:@"url"] !=[NSNull null] &&

        [[aps objectForKey:@"url"] length] > 0 ) {

        NSLog(@"About to Open Safari");

        // NSString *urlLink=[[NSString alloc]initWithString:[aps objectForKey:@"url"]];

        NSString *urlLink=[NSString stringWithFormat:

                           @"%@",[aps objectForKey:@"url"]];

        NSURL *url = [NSURL URLWithString:urlLink];

        if (![[UIApplication sharedApplication] openURL:url]) {

            NSLog(@"Failed to open url:%@",[url description]);

        }

    }

    

    if ([notification objectForKey:@"job_id"])

    {

        // do something with job id

        int jobID = [[notification objectForKey:@"job_id"] intValue];

        NSLog(@"int jobID");

    }

    

}

 

 

@end




送信方法(json)

送信の仕方は以下のjson形式になります。
そのまま貼り付けて使用できます。
通知をタップすると指定のURLに飛びます。
またアプリの使用中であったりバックグラウンド、タスクキルの状態であっても同様です。

 {
     "aps": {
          "badge": 1,
          "alert": "我讨厌苹果😊",
          "sound": "cat.caf",
           "url": "https://taiwan-travel.net"
 

     },
     "job_id": 1
 }

 

 

 

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

CAPTCHA