I have an app in development and I think I have done enough to receive push notifications, but it ain't happening as of now. I have coded the AppDelegate.m accordingly but I don't see it working:
AppDelegate.m
#import "AppDelegate.h"
#import "InfosyncBaseViewController.h"
// Data submission.
#import "Record.h"
#import "ManagedObjectUtilities.h"
#import "RecordBO.h"
// Data sync.
#import "UserBO.h"
#import "FolderBO.h"
#import "SyncUtilities.h"
#import "FormBO.h"
#import "UserFolder.h"
#import "UserForm.h"
#import "ErrorMsgUtilities.h"
// Google Maps!
#import <GoogleMaps/GoogleMaps.h>
//Debugging
#define LOG_LEVEL_DEF ddLogLevel
#import <CocoaLumberjack/CocoaLumberjack.h>
//PushNotification Firebase
@import Firebase;
@import FirebaseMessaging;
@import FirebaseInstanceID;
@interface AppDelegate ()
{
NSString *InstanceID;
}
@property (nonatomic, strong) NSString *strUUID;
@property (nonatomic, strong) NSString *strDeviceToken;
@end
@implementation AppDelegate
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
@synthesize id_forms = _id_forms;
@synthesize lastError = _lastError;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//push !!
// Register for remote notifications
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
// iOS 7.1 or earlier
UIRemoteNotificationType allNotificationTypes =(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound);
[application registerForRemoteNotificationTypes:allNotificationTypes];
} else {
// iOS 8 or later
// [END_EXCLUDE]
UIUserNotificationType allNotificationTypes = (UIRemoteNotificationTypeNewsstandContentAvailability|
UIUserNotificationTypeBadge |
UIUserNotificationTypeSound |
UIUserNotificationTypeAlert);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
// [START configure_firebase]
[FIRApp configure];
// [END configure_firebase]
// Add observer for InstanceID token refresh callback.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:)
name:kFIRInstanceIDTokenRefreshNotification object:nil];
[DDLog addLogger:[DDASLLogger sharedInstance]];
[DDLog addLogger:[DDTTYLogger sharedInstance]];
// Override point for customization after application launch.
InfosyncBaseViewController *loginController = (InfosyncBaseViewController*)self.window.rootViewController;
loginController.managedObjectContext = self.managedObjectContext;
[GMSServices provideAPIKey:GOOGLE_MAPS_API_KEY];
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
#ifdef __IPHONE_8_0
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert
| UIUserNotificationTypeBadge
| UIUserNotificationTypeSound) categories:nil];
[application registerUserNotificationSettings:settings];
#endif
} else {
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
[application registerForRemoteNotificationTypes:myTypes];
}
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
return YES;
}
- (void)registerUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
DebugLog(@"push notif");
}
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
NSLog(@"########### Received Background Fetch ###########");
//Download the Content .
//Cleanup
completionHandler(UIBackgroundFetchResultNewData);
}
- (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.
[[AFNetworkReachabilityManager sharedManager] stopMonitoring];
[[EDQueue sharedInstance] stop];
#ifdef DEBUG_MODE
#ifdef ENABLE_UIVIEWSHOWALIGNMENTRECTS_SETTING
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"UIViewShowAlignmentRects"];
#endif // ENABLE_UIVIEWSHOWALIGNMENTRECTS_SETTING
#endif // DEBUG_MODE
}
- (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.
[[FIRMessaging messaging] disconnect];
NSLog(@"Disconnected from FCM");
}
- (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.applicationIconBadgeNumber = 0;
}
- (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 = 0;
[self connectToFcm];
[[EDQueue sharedInstance] setDelegate:self];
[[EDQueue sharedInstance] start];
// Starting to monitor that we can reach the Internet.
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN:
// Edge / 3g / 4g available.
if (![AFNetworkReachabilityManager sharedManager].isReachableViaWiFi) {
// WiFi not available!
// Checking if celullar transmission is allowed.
User *loggedInUser = [UserBO loggedInUser];
if (![loggedInUser.syncOver3g boolValue]) {
// Syncing over celullar not allowed.
// Cancelling queue.
[[EDQueue sharedInstance] empty];
}
}
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
// WiFi available. Not doing anything. Connections will jump to WiFi.
break;
case AFNetworkReachabilityStatusNotReachable:
default:
// This will fail on whatever connections we had set up.
break;
}
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
#ifdef DEBUG_MODE
#ifdef ENABLE_UIVIEWSHOWALIGNMENTRECTS_SETTING
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"UIViewShowAlignmentRects"];
#endif // ENABLE_UIVIEWSHOWALIGNMENTRECTS_SETTING
#endif // DEBUG_MODE
}
//Push Messages test?
// [START receive_message]
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// 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);
//Success
completionHandler(UIBackgroundFetchResultNewData);
}
// [END receive_message]
// [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);
// Connect to FCM since connection may have failed when attempted before having a token.
[self connectToFcm];
// TODO: If necessary send token to appliation server.
}
// [END refresh_token]
// [START connect_to_fcm]
- (void)connectToFcm {
[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(@"Unable to connect to FCM. %@", error);
} else {
NSLog(@"Connected to FCM.");
}
}];
}
//push
// system push notification registration success callback, delegate to pushManager
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeProd];
//push//NSLog(@"deviceToken1 = %@",deviceToken);
[application registerForRemoteNotifications];
}
// system push notification registration error callback, delegate to pushManager
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
//[[PushNotificationManager pushManager] handlePushRegistrationFailure:error];
}
// system push notifications callback, delegate to pushManager
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
//[[PushNotificationManager pushManager] handlePushReceived:userInfo];
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
UIUserNotificationType types = (UIUserNotificationType) (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert);
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
if (application.applicationState == UIApplicationStateActive) {
if ([notification.alertBody isEqualToString:@""]) {
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"companyName", @"InfoSync")
message:notification.alertBody
delegate:self
cancelButtonTitle:NSLocalizedString(@"Ok", @"Aceptar")
otherButtonTitles:nil];
[alert show];
}
}else if (application.applicationState != UIApplicationStateActive){
// For present a specific controller after localNotification
// Ref.: https://hellomihai.wordpress.com/2015/02/26/opening-a-view-when-app-is-launched-from-a-local-notification-ios7-ios8/
// For now lost menu fuctionality
// if (application.applicationState != UIApplicationStateActive) { // only if not active
// UIViewController *myDesiredView = [self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:@"Whatever id from storyboard"];
// [self.window.rootViewController showViewController:myDesiredView sender:self];
//
// }
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"companyName", @"InfoSync")
message:NSLocalizedString(@"Your information no sent. Please try again in completed records.",@"No se pudo enviar la información. Favor de reintentar desde la pestaña de Registros completados")
delegate:self cancelButtonTitle:NSLocalizedString(@"Ok", @"Aceptar")
otherButtonTitles:nil];
[alert show];
}
// Set icon badge number to zero
application.applicationIconBadgeNumber = 0;
}
-(void)sendNotification:(NSString*)notificationAlertBody
{
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [ NSDate dateWithTimeIntervalSinceNow:5];
localNotification.alertBody = notificationAlertBody;
localNotification.alertAction = NSLocalizedString(@"companyName", @"InfoSync");
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
@end
Any help? Objective-c is not my language I'm a beginer. Thanks.