我正在使用FCM推送我的项目通知。当应用程序与XCode一起安装时,一切正常。我可以收到推送通知。 我将我的应用程序上传到testFlight后。然后推送通知只能推一次。在那之后,我再也收不到任何消息了。 下面是我在AppDelegate中的代码。
#import "AppDelegate.h"
#import "Definition.h"
#import "Message.h"
// FCM
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
@import UserNotifications;
#endif
@import Firebase;
@import FirebaseInstanceID;
@import FirebaseMessaging;
// Implement UNUserNotificationCenterDelegate to receive display notification via APNS for devices
// running iOS 10 and above. Implement FIRMessagingDelegate to receive data message via FCM for
// devices running iOS 10 and above.
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
@interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
@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
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// ------------------------------------------------------
// FCM Setting
// ------------------------------------------------------
// Register for remote notifications
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
// iOS 7.1 or earlier. Disable the deprecation warnings.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
UIRemoteNotificationType allNotificationTypes =
(UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge);
[application registerForRemoteNotificationTypes:allNotificationTypes];
#pragma clang diagnostic pop
} else {
// iOS 8 or later
// [START register_for_notifications]
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
}
[[UIApplication sharedApplication] registerForRemoteNotifications];
// [END register_for_notifications]
}
// [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];
return YES;
}
// FCM
// [START receive_message]
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// 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
[self pushNotificationAction:userInfo sender:@"ID1(bgtap)"];
}
- (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
[self pushNotificationAction:userInfo sender:@"ID2(bgtap)"];
}
// [END receive_message]
// [START ios_10_message_handling]
// Receive displayed notifications for iOS 10 devices.
#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 {
NSDictionary *userInfo = notification.request.content.userInfo;
[self pushNotificationAction:userInfo sender:@"ID3"];
}
// 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;
[self pushNotificationAction:userInfo sender:@"ID4"];
}
#endif
// [END ios_10_message_handling]
// [START ios_10_data_message_handling]
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// Receive data message on iOS 10 devices while app is in the foreground.
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
// Print full message
[self pushNotificationAction:[remoteMessage appData] sender:@"fcm"];
}
#endif
// [END ios_10_data_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);
if(![refreshedToken isEqualToString:@""]){
[Utility setValue:refreshedToken key:@"fcmtoken"];
[self connectToFcm];
}
// TODO: If necessary send token to application 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.");
}
}];
}
#pragma mark - Push notification action
- (void) pushNotificationAction:(NSDictionary *)userInfo sender:(NSString *)sender {
// Log
NSString *logMessage = [NSString stringWithFormat:@"%@: %@",sender,userInfo];
NSLog(@"%@",logMessage);
// FCM type
NSString *tag = [userInfo valueForKey:@"sync"];
NSLog(@"FCM type=%@",tag);
// type snyc
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTheTableM3" object:nil userInfo:userInfo];
if([tag isEqualToString:@"all"] || YES){
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTheTableM3" object:nil userInfo:userInfo];
}
// type other
if(tag == nil){
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTheTableM1" object:nil userInfo:userInfo];
NSMutableArray *test = [NSMutableArray arrayWithObjects:userInfo, nil];
if([test count]>0){
Message *message = [[Message alloc] init];
[message insert:message];
}
}
}
// [END connect_to_fcm]
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"Unable to register for remote notifications: %@", error);
}
// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the InstanceID token.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(@"APNs token retrieved: %@", deviceToken);
// token 存進去
NSString *test = [NSString stringWithFormat:@"%@",deviceToken];
[Utility setValue:test key:@"pushtoken"];
NSString *refreshedToken = [[FIRInstanceID instanceID] token];
if(![refreshedToken isEqualToString:@""]){
[Utility setValue:refreshedToken key:@"fcmtoken"];
[[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeUnknown];
}
NSLog(@"FCMs toke %@",refreshedToken);
// With swizzling disabled you must set the APNs token here.
// for development
//[[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
// for production
//[[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeProd];
[self connectToFcm];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
[self connectToFcm];
}
// [START disconnect_from_fcm]
- (void)applicationDidEnterBackground:(UIApplication *)application {
//[[FIRMessaging messaging] disconnect];
//NSLog(@"Disconnected from FCM");
NSLog(@"Move to Background");
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
}
// [END disconnect_from_fcm]
// FCM結束
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
答案 0 :(得分:0)
更改此行FIRInstanceIDAPNSTokenTypeUnknown
for Sandbox(开发) - FIRInstanceIDAPNSTokenTypeSandbox
,对于Adhoc,testFlight和App Store使用以下 - FIRInstanceIDAPNSTokenTypeProd
尝试如果问题未解决则请问我