Don't receive push notifications with GCM on iOS - ios

I followed this tutorial https://developers.google.com/cloud-messaging/ios/client to implement Google Cloud Messaging on my iOS application. I use google app engine as server side and the java library for GCM to send messages and it works perfectly for my Android application. However my iOS application does not receive messages from it.
I don't understand why because I do get the registration token and send it to my server side. I don't get any error log. Here is my AppDelegate.m code:
#import "AppDelegate.h"
#interface AppDelegate ()
#property (nonatomic, strong) NSDictionary *registrationOptions;
#property (nonatomic, strong) GGLInstanceIDTokenHandler registrationHandler;
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//-- Start the GCMService
[[GCMService sharedInstance] startWithConfig:[GCMConfig defaultConfig]];
if ([application respondsToSelector:#selector(isRegisteredForRemoteNotifications)])
{
// iOS 8 Notifications
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[application registerForRemoteNotifications];
}
else
{
// iOS < 8 Notifications
[application registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
}
self.registrationHandler = ^(NSString *registrationToken, NSError *error){
if (registrationToken != nil) {
//I do get the token, and I can store it
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:registrationToken forKey:CLE_TOKENGCM];
NSLog(#"Registration Token: %#", registrationToken);
} else {
NSLog(#"Registration to GCM failed with error: %#", error.localizedDescription);
}
};
return YES;
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
// Start the GGLInstanceID shared instance with the default config and request a registration
// token to enable reception of notifications
NSLog(#"didRegisterForRemoteNotificationsWithDeviceToken");
[[GGLInstanceID sharedInstance] startWithConfig:[GGLInstanceIDConfig defaultConfig]];
self.registrationOptions = #{kGGLInstanceIDRegisterAPNSOption:deviceToken,
kGGLInstanceIDAPNSServerTypeSandboxOption:#NO};//I tried both YES and NO value
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:SENDER_ID
scope:kGGLInstanceIDScopeGCM
options:self.registrationOptions
handler:self.registrationHandler];
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSLog(#"Error in registration. Error: %#", err);
}
- (void)onTokenRefresh {
// A rotation of the registration tokens is happening, so the app needs to request a new token.
NSLog(#"The GCM registration token needs to be changed.");
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:SENDER_ID
scope:kGGLInstanceIDScopeGCM
options:self.registrationOptions
handler:self.registrationHandler];
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
NSLog(#"Notification received: %#", userInfo);//This log never prints so the method is never called
// This works only if the app started the GCM service
[[GCMService sharedInstance] appDidReceiveMessage:userInfo];
// Handle the received message
// Invoke the completion handler passing the appropriate UIBackgroundFetchResult value
// ...
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"Notification received: %#", userInfo);//This log never prints so the method is never called
// This works only if the app started the GCM service
[[GCMService sharedInstance] appDidReceiveMessage:userInfo];
// Handle the received message
// Invoke the completion handler passing the appropriate UIBackgroundFetchResult value
// ...
}
#end

Thanks to ztan comment and to the Google GCM sample, I found out what was wrong: I had to implement applicationDidBecomeActive: like this:
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Connect to the GCM server to receive non-APNS notifications
[[GCMService sharedInstance] connectWithHandler:^(NSError *error) {
if (error) {
NSLog(#"Could not connect to GCM: %#", error.localizedDescription);
} else {
NSLog(#"Connected to GCM");
// ...
}
}];
}

Related

Device token for push notifications not generated

Since a few days, I am unable to receive push notifications for one of my apps. I had a closer look and it seems it doesn't manage to generate a device token. I was able to reproduce it with a blank application and the following code (or the Swift equivalent):
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
NSLog(#"Granted.");
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
});
} else {
NSLog(#"Not granted.");
}
}];
return YES;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"Token: %#", deviceToken);
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(#"Error: %#", error);
}
Push notifications were added to the app's capabilities (I've blanked out the team name and part of the certificate description):
and this generated the following entitlements file:
When the app launches, I get the usual popup:
and the app reaches the 'Granted' block:
2022-06-12 19:55:28.665018+0200 Sandbox[1704:108535] Granted.
but I see neither a device token nor an error in the log.

Issue subscribing to FCM topic using Xcode/Objective C

I have a problem which I've been unable to resolve. My knowledge of iOS/Xcode is limited, please forgive me.
I am trying to subscribe to an FCM topic for an iOS app using xcode/Objective C but when loading the App, it is not subscribing to the topic, in the debugger it doesn't even look like it is trying.
If I move the [[FIRMessaging messaging] subscribeToTopic:#"/topics/channel"];
line to just below
[FIRMessaging messaging].delegate = self;
[application registerForRemoteNotifications];
[FIRApp configure];
(and above return YES;) then at least I get this error message indicating that it is at least trying.
2018-01-04 04:00:18.723760+0000 App[1049:1251125] [Firebase/Messaging][I-FCM002010] Cannot subscribe to topic: /topics/channel with token: (null)
So following the suggestion here (and a number of other places), I have tried to move it out into didRegisterUserNotificationSettings but it doesn't seem to be doing anything at all and there is no trace of it in the debugger.
This is my full AppDelegate.m code
//
// AppDelegate.m
//
#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>
#import <Firebase/Firebase.h>
#import <FirebaseMessaging/FirebaseMessaging.h>
#import <FirebaseInstanceID/FirebaseInstanceID.h>
#import <AFNetworking/AFNetworking.h>
#import Firebase;
#interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self setupNetworkReachability];
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error)
{
}];
[FIRMessaging messaging].delegate = self;
[application registerForRemoteNotifications];
[FIRApp configure];
//[[FIRMessaging messaging] subscribeToTopic:#"/topics/channel"];
return YES;
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UNNotificationSettings *)notificationSettings
{
[[FIRMessaging messaging] subscribeToTopic:#"/topics/channel"];
NSLog(#"Topic Registered");
}
- (void)applicationWillResignActive:(UIApplication *)application
{
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
}
- (void)applicationWillTerminate:(UIApplication *)application
{
}
#pragma mark - Public Methods
+ (AppDelegate *)sharedAppDelegate
{
return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
- (void)setupNetworkReachability
{
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{
if (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN)
self.isNetworkAvailable = YES;
else
self.isNetworkAvailable = NO;
NSLog(#"Reachability: %#", AFStringFromNetworkReachabilityStatus(status));
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
}
#pragma mark - FIRMessagingDelegate Methods
- (void)messaging:(nonnull FIRMessaging *)messaging didReceiveMessage:(nonnull FIRMessagingRemoteMessage *)remoteMessage
{
NSLog(#"%#", remoteMessage.appData);
}
- (void)applicationReceivedRemoteMessage:(nonnull FIRMessagingRemoteMessage *)remoteMessage
{
NSLog(#"%#", remoteMessage.appData);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
NSLog(#"%#", notification.request.content.userInfo);
completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound);
}
#end
Would appreciate any help. Thank you.
Just to update, the App already receives message directly from FCM console, so that part works OK, it is just the topic subscription that is failing.
1: You should call [FIRApp configure]; before [FIRMessaging messaging].delegate = self;
2: As you post full code of your AppDelegate.m file. So it is missing the below method to update/send token to Firebase. You will receive a TOKEN with in this UIApplication's delegate method and you have to set it for Firebase (Just put this method in your AppDelegate.m file)
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSString *strDevicetoken = [[NSString alloc]initWithFormat:#"%#",[[[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]] stringByReplacingOccurrencesOfString:#" " withString:#""]];
NSLog(#"Device Token = %#",strDevicetoken);
[FIRMessaging messaging].APNSToken = deviceToken;
//NSString *fcmToken = [FIRMessaging messaging].FCMToken;
//NSLog(#"FCM registration token: %#", fcmToken);
}
Now you have successfully set APNS Token at Firebase and you can now subscribe to your desired topic at Firebase

Firebase ios notification token not generated in objective c

I completed all the steps followed by firebase notification document, finally when I run the app.showing the following error, how to generate device token? please refer screenshot below
Error:
Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
I tried this code
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
[[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:156.0/255.0 green:39.0/255.0 blue:176.0/255.0 alpha:1.0]];
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} 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] setDelegate:self];
// For iOS 10 data message (sent via FCM)
[[FIRMessaging messaging] setRemoteMessageDelegate:self];
#endif
}
[FIRApp configure];
// Add observer for InstanceID token refresh callback.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(tokenRefreshNotification:)
name:kFIRInstanceIDTokenRefreshNotification object:nil];
// [[UIApplication sharedApplication] registerForRemoteNotifications];
[[UIApplication sharedApplication] unregisterForRemoteNotifications];
return YES;
}
- (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)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.
[self connectToFcm];
}
- (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 application server.
}
// With "FirebaseAppDelegateProxyEnabled": NO
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[[FIRInstanceID instanceID] setAPNSToken:deviceToken
type:FIRInstanceIDAPNSTokenTypeSandbox];
}
- (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);
}
- (void)connectToFcm {
[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Unable to connect to FCM. %#", error);
} else {
NSLog(#"Connected to FCM.");
}
}];
}
console screenshot:

GCM Registration token in iOS

I am completely new to GCM integration with iOS i have an GCMSENDERID all i want to get registration token with this sender id.The function is also not getting called.let me know what mistake i have done or please give me some examples to sort it out.
#import "AppDelegate.h"
static NSString *const INSTANCE_ID_REGISTRATION_NOTIF_KEY = #"instance-id-token";
static NSString *const GCM_SENDER_ID = #"19398749911";
#interface AppDelegate ()
{
}
#property (nonatomic, strong) NSDictionary *registrationOptions;
#property (nonatomic, strong) GGLInstanceIDTokenHandler registrationHandler;
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
UIUserNotificationType allNotificationTypes=(UIUserNotificationTypeSound|UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings=[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication]registerUserNotificationSettings:settings];
[[UIApplication sharedApplication]registerForRemoteNotifications];
self.registrationHandler = ^(NSString *registrationToken, NSError *error){
if (registrationToken != nil) {
//I do get the token, and I can store it
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:registrationToken forKey:INSTANCE_ID_REGISTRATION_NOTIF_KEY];
NSLog(#"Registration Token: %#", registrationToken);
} else {
NSLog(#"Registration to GCM failed with error: %#", error.localizedDescription);
}
};
return YES;
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
// Start the GGLInstanceID shared instance with the default config and request a registration
// token to enable reception of notifications
NSLog(#"didRegisterForRemoteNotificationsWithDeviceToken");
[[GGLInstanceID sharedInstance] startWithConfig:[GGLInstanceIDConfig defaultConfig]];
self.registrationOptions = #{kGGLInstanceIDRegisterAPNSOption:deviceToken,
kGGLInstanceIDAPNSServerTypeSandboxOption:#NO};//I tried both YES and NO value
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:GCM_SENDER_ID
scope:kGGLInstanceIDScopeGCM
options:self.registrationOptions
handler:self.registrationHandler];
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSLog(#"Error in registration. Error: %#", err);
}
- (void)onTokenRefresh {
// A rotation of the registration tokens is happening, so the app needs to request a new token.
NSLog(#"The GCM registration token needs to be changed.");
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:GCM_SENDER_ID
scope:kGGLInstanceIDScopeGCM
options:self.registrationOptions
handler:self.registrationHandler];
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
NSLog(#"Notification received: %#", userInfo);//This log never prints so the method is never called
// This works only if the app started the GCM service
[[GCMService sharedInstance] appDidReceiveMessage:userInfo];
// Handle the received message
// Invoke the completion handler passing the appropriate UIBackgroundFetchResult value
// ...
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"Notification received: %#", userInfo);//This log never prints so the method is never called
// This works only if the app started the GCM service
[[GCMService sharedInstance] appDidReceiveMessage:userInfo];
// Handle the received message
// Invoke the completion handler passing the appropriate UIBackgroundFetchResult value
// ...
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Connect to the GCM server to receive non-APNS notifications
[[GCMService sharedInstance] connectWithHandler:^(NSError *error) {
if (error) {
NSLog(#"Could not connect to GCM: %#", error.localizedDescription);
} else {
NSLog(#"Connected to GCM");
// ...
}
}];
}

How do i get my push notification to play a sound as soon as it is received?

App A is pushing a notification to App B like so:
NSDictionary *data = #{
#"alert" : #"Purchase Successful! 1 Remove Ads",
#"badge" : #"Increment",
#"sounds" : #"Bell.caf",
};
PFPush *push = [[PFPush alloc] init];
[push setChannels:#[ #"Mets" ]];
[push setData:data];
[push sendPushInBackground];
App B Receives the push notification like so:
//
// ParseStarterProjectAppDelegate.m
//
// Copyright 2011-present Parse Inc. All rights reserved.
//
#import <Parse/Parse.h>
// If you want to use any of the UI components, uncomment this line
// #import <ParseUI/ParseUI.h>
// If you are using Facebook, uncomment this line
// #import <ParseFacebookUtils/PFFacebookUtils.h>
// If you want to use Crash Reporting - uncomment this line
// #import <ParseCrashReporting/ParseCrashReporting.h>
#import "ParseStarterProjectAppDelegate.h"
#import "ParseStarterProjectViewController.h"
#implementation ParseStarterProjectAppDelegate
#pragma mark -
#pragma mark UIApplicationDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Enable storing and querying data from Local Datastore. Remove this line if you don't want to
// use Local Datastore features or want to use cachePolicy.
[Parse enableLocalDatastore];
// ****************************************************************************
// Uncomment this line if you want to enable Crash Reporting
// [ParseCrashReporting enable];
//
// Uncomment and fill in with your Parse credentials:
[Parse setApplicationId:#"APPIDHERE" clientKey:#"CLIENTKEYHERE"];
//
// If you are using Facebook, uncomment and add your FacebookAppID to your bundle's plist as
// described here: https://developers.facebook.com/docs/getting-started/facebook-sdk-for-ios/
// [PFFacebookUtils initializeFacebook];
// ****************************************************************************
[PFUser enableAutomaticUser];
PFACL *defaultACL = [PFACL ACL];
// If you would like all objects to be private by default, remove this line.
[defaultACL setPublicReadAccess:YES];
[PFACL setDefaultACL:defaultACL withAccessForCurrentUser:YES];
// Override point for customization after application launch.
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
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 __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([application respondsToSelector:#selector(registerUserNotificationSettings:)]) {
UIUserNotificationType userNotificationTypes = (UIUserNotificationTypeAlert |
UIUserNotificationTypeBadge |
UIUserNotificationTypeSound);
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:userNotificationTypes
categories:nil];
[application registerUserNotificationSettings:settings];
[application registerForRemoteNotifications];
} else
#endif
{
[application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound)];
}
return YES;
}
#pragma mark Push Notifications
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
[currentInstallation setDeviceTokenFromData:deviceToken];
[currentInstallation saveInBackground];
[PFPush subscribeToChannelInBackground:#"Mets" block:^(BOOL succeeded, NSError *error) {
if (succeeded) {
NSLog(#"ParseStarterProject successfully subscribed to push notifications on the broadcast channel.");
} else {
NSLog(#"ParseStarterProject failed to subscribe to push notifications on the broadcast channel.");
}
}];
}
- (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);
}
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[PFPush handlePush:userInfo];
if (application.applicationState == UIApplicationStateInactive) {
[PFAnalytics trackAppOpenedWithRemoteNotificationPayload:userInfo];
}
}
///////////////////////////////////////////////////////////
// Uncomment this method if you want to use Push Notifications with Background App Refresh
///////////////////////////////////////////////////////////
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// if (application.applicationState == UIApplicationStateInactive) {
// [PFAnalytics trackAppOpenedWithRemoteNotificationPayload:userInfo];
// }
//}
#pragma mark Facebook SDK Integration
///////////////////////////////////////////////////////////
// Uncomment this method if you are using Facebook
///////////////////////////////////////////////////////////
//- (BOOL)application:(UIApplication *)application
// openURL:(NSURL *)url
// sourceApplication:(NSString *)sourceApplication
// annotation:(id)annotation {
// return [PFFacebookUtils handleOpenURL:url];
//}
#end
How come I don't hear any sounds go off when App B receive's the push notification? No sound is played when the app is closed and the banner notification appears (which I'd like a sound), no sound is played when the app is open and the notification appears (just a vibrate, that's odd). Why is that and how do I fix it?
Do it like this:
NSDictionary *data = #{
#"alert" : #"you daily milk temp",
#"badge" : #"Increment",
#"sound" : #"super.caf"
};
PFPush *pusher = [[PFPush alloc] init];
[pusher setChannels:#[ #"deviceTemperatureReading" ]];
[pusher setData:data];
[pusher sendPushInBackground];
"super.caf" is a sound file

Resources