#import "AppDelegate.h" #import "LauncherViewController.h" #import "EmbaixadoresEndPoint.h" #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 @import UserNotifications; #endif // Implement UNUserNotificationCenterDelegate to receive display notification via APNS for devices // running iOS 10 and above. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 @interface AppDelegate () @end #endif // Copied from Apple's header in case it is missing in some cases (e.g. pre-Xcode 8 builds). #ifndef NSFoundationVersionNumber_iOS_9_x_Max #define NSFoundationVersionNumber_iOS_9_x_Max 1299 #endif @implementation AppDelegate NSString *const kGCMMessageIDKey = @"gcm.message_id"; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSUserDefaults *session = [NSUserDefaults standardUserDefaults]; NSString *token = [session stringForKey:@"gcm_token"]; [self registerRemoteNotification: application]; /* NSString *t = [[FIRInstanceID instanceID] token]; if(t) { [self connectToFcm]; } */ self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds]; self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.backgroundColor = [UIColor whiteColor]; self.window.rootViewController = [[LauncherViewController alloc] init]; [self.window makeKeyAndVisible]; 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. } - (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 { NSLog(@"Foreground"); // 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. } - (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. //application.applicationIconBadgeNumber -= 1; } - (void)applicationWillTerminate:(UIApplication *)application { NSLog(@"terminate"); // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } - (void)registerRemoteNotification:(UIApplication *)application { // Register for remote notifications. This shows a permission dialog on first run, to // show the dialog at a more appropriate time move this registration accordingly. // [START configure_firebase] [FIRApp configure]; // [END configure_firebase] [FIRMessaging messaging].remoteMessageDelegate = self; if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) { UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]; [application registerUserNotificationSettings:settings]; //[application registerForRemoteNotifications]; } else { // iOS 10 or later #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge; [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) { }]; // For iOS 10 display notification (sent via APNS) [UNUserNotificationCenter currentNotificationCenter].delegate = self; // For iOS 10 data message (sent via FCM) #endif // [END register_for_notifications] } [application registerForRemoteNotifications]; // Add observer for InstanceID token refresh callback. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:) name:kFIRInstanceIDTokenRefreshNotification object:nil]; [self connectToFcm]; } // [START message_handling] // Receive displayed notifications for iOS 10 devices. // Note on the pragma: When compiling with iOS 10 SDK, include methods that // handle notifications using notification center. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Handle incoming notification messages while app is in the foreground. - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { // Print message ID. NSDictionary *userInfo = notification.request.content.userInfo; if (userInfo[kGCMMessageIDKey]) { NSLog(@"Message ID 1: %@", userInfo[kGCMMessageIDKey]); } // Print full message. NSLog(@"%@", userInfo); NSError *error; NSDictionary *userInfoMutable = [userInfo mutableCopy]; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInfoMutable options:0 error:&error]; //[UIApplication sharedApplication].applicationIconBadgeNumber += 1; NSLog(@"APP WAS CLOSED DURING PUSH RECEPTION Saved data: %@", jsonData); // Change this to your preferred presentation option completionHandler(UNNotificationPresentationOptionAlert); } // Handle notification messages after display notification is tapped by the user. - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler { NSDictionary *userInfo = response.notification.request.content.userInfo; if (userInfo[kGCMMessageIDKey]) { NSLog(@"Message ID 2: %@", userInfo[kGCMMessageIDKey]); } // Print full message. NSLog(@"aaa%@", userInfo); NSError *error; NSDictionary *userInfoMutable = [userInfo mutableCopy]; NSLog(@"New method with push callback: %@", userInfo); [userInfoMutable setValue:@(YES) forKey:@"wasTapped"]; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInfoMutable options:0 error:&error]; NSLog(@"APP WAS CLOSED DURING PUSH RECEPTION Saved data: %@", jsonData); completionHandler(); } #endif - (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(nonnull NSDictionary *)userInfo completionHandler:(nonnull void (^)())completionHandler { [self application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler]; } // [START receive_message in background iOS < 10] // Include the iOS < 10 methods for handling notifications for when running on iOS < 10. // As in, even if you compile with iOS 10 SDK, when running on iOS 9 the only way to get // notifications is the didReceiveRemoteNotification. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { // Short-circuit when actually running iOS 10+, let notification centre methods handle the notification. if (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_9_x_Max) { return; } /* NSLog(@"Message ID: %@", userInfo[@"gcm.message_id"]); if (application.applicationState != UIApplicationStateActive) { } else { }*/ [self application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:^(UIBackgroundFetchResult result) { }]; } // [END receive_message in background] iOS < 10] // [START receive_message iOS < 10] - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { // Short-circuit when actually running iOS 10+, let notification centre methods handle the notification. if (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_9_x_Max) { return; } // If you are receiving a notification message while your app is in the background, // this callback will not be fired till the user taps on the notification launching the application. // TODO: Handle data of notification // Print message ID. NSLog(@"Message ID: %@", userInfo[@"gcm.message_id"]); // Pring full message. NSLog(@"%@", userInfo); NSDictionary *appData = [userInfo mutableCopy]; // Has user tapped the notificaiton? // UIApplicationStateActive - app is currently active // UIApplicationStateInactive - app is transitioning from background to // foreground (user taps notification) NSInteger badge = application.applicationIconBadgeNumber; badge++; //application.applicationIconBadgeNumber = badge; UIApplicationState state = application.applicationState; //if (state == UIApplicationStateActive || state == UIApplicationStateInactive) { if (state == UIApplicationStateBackground) { [appData setValue:@(NO) forKey:@"wasTapped"]; NSString *title = [[appData objectForKey:@"notification"] objectForKey:@"title"]; NSString *body = [[appData objectForKey:@"notification"] objectForKey:@"body"]; UILocalNotification* content = [[UILocalNotification alloc] init]; content.fireDate = [[NSDate date] dateByAddingTimeInterval:5.0f]; content.alertTitle = (title && ![@"" isEqualToString:title]) ? title : @"Embaixadores Cielo"; content.repeatInterval = kCFCalendarUnitDay; content.alertBody = body; content.userInfo = @{}; content.soundName= UILocalNotificationDefaultSoundName; content.timeZone = [NSTimeZone defaultTimeZone]; //content.applicationIconBadgeNumber = badge; [application scheduleLocalNotification:content]; } completionHandler(UIBackgroundFetchResultNoData); } // [END receive_message iOS < 10] // [END message_handling] // [START refresh_token] - (void)tokenRefreshNotification:(NSNotification *)notification { // Note that this callback will be fired everytime a new token is generated, including the first // time. So if you need to retrieve the token as soon as it is available this is where that // should be done. NSString *refreshedToken = [[FIRInstanceID instanceID] token]; NSLog(@"InstanceID token: %@", refreshedToken); NSUserDefaults *session = [NSUserDefaults standardUserDefaults]; [session setObject:refreshedToken forKey:@"gcm_token"]; // Connect to FCM since connection may have failed when attempted before having a token. [self connectToFcm]; // TODO: If necessary send token to appliation server. EmbaixadoresEndPoint *endpoint = [[EmbaixadoresEndPoint alloc] init]; [endpoint registrationToServer:nil push:refreshedToken handler:^(NSError *error) { NSLog(@"embaixadoresEndPoint - resp: %@", error); }]; } // [END refresh_token] // [START connect_to_fcm] - (void)connectToFcm { // Won't connect since there is no token if (![[FIRInstanceID instanceID] token]) { return; } // Disconnect previous FCM connection if it exists. [[FIRMessaging messaging] disconnect]; [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) { if (error != nil) { NSLog(@"Unable to connect to FCM. %@", error); } else { NSLog(@"Connected to FCM."); } }]; } // [END connect_to_fcm] - (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage { NSLog(@"APNs device token retrieved: %@", remoteMessage); NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber; badge++; //[UIApplication sharedApplication].applicationIconBadgeNumber = badge; NSDictionary *appData = remoteMessage.appData; NSString *title = [[appData objectForKey:@"notification"] objectForKey:@"title"]; NSString *body = [[appData objectForKey:@"notification"] objectForKey:@"body"]; UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init]; content.title = (title && ![@"" isEqualToString:title]) ? title : @"Embaixadores Cielo"; content.sound = [UNNotificationSound defaultSound]; content.badge = [NSNumber numberWithInteger:badge]; content.body = body; content.userInfo = [appData objectForKey:@"data"]; content.categoryIdentifier = @"message"; UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5.0f repeats:NO]; UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"PUSH" content:content trigger:trigger]; [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil]; /*UNUserNotificationCenter.current().add( request, withCompletionHandler: nil)*/ } @end