简体   繁体   English

在iOS中未收到FCM通知

[英]FCM notification not receiving in iOS

I have been trying to get firebase push-notification in my ios app for a long time. 我一直试图在我的ios应用程序中获取firebase推送通知很长一段时间。 I have tried everything on the internet I could find. 我已经尝试了我能找到的互联网上的一切。 But sadly no luck. 但遗憾的是没有运气。 Any help would be appreciated. 任何帮助,将不胜感激。

I am sending notification through firebase console. 我通过firebase控制台发送通知。

and here is my code: 这是我的代码:

#import "AppDelegate.h"

#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
@import UserNotifications;
#endif

@import Firebase;
@import FirebaseInstanceID;
@import FirebaseMessaging;

#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
@interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
@end
#endif

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    // [START configure_firebase]
    [FIRApp configure];
    // [END configure_firebase]

    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];

    // Add observer for InstanceID token refresh callback.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:)
                                                 name:kFIRInstanceIDTokenRefreshNotification object:nil];

    return YES;
}

// [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);

    NSLog(@"id = ---------- %@",[[[UIDevice currentDevice] identifierForVendor] UUIDString]);


    [[NSNotificationCenter defaultCenter] postNotificationName:@"fcmtoken" object: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.
}
// [END refresh_token]

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

    // Print message ID.
    NSLog(@"Message ID: %@", userInfo[@"gcm.message_id"]);

    // Print full message.
    NSLog(@"didReceiveRemoteNotification= %@", userInfo);
}

// [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
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    // Print message ID.
    NSDictionary *userInfo = notification.request.content.userInfo;
    NSLog(@"Message ID: %@", userInfo[@"gcm.message_id"]);

    // Print full message.
    NSLog(@"willPresentNotification: %@", userInfo);
}

// Receive data message on iOS 10 devices.
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
    // Print full message
    NSLog(@"message Recived = %@", [remoteMessage appData]);

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ROFL"
                                                    message:@"Dee dee doo doo."
                                                   delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];

}
#endif

// [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.");
        }
    }];
}
// [END connect_to_fcm]

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

    NSLog(@"didRegisterForRemoteNotificationsWithDeviceToken");
    // for development
    [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];

    // for production
    //     [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeProd];


}

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

    [self connectToFcm];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

In the log i am able to see Token generated for my device, also when i send notification to token app doesn't receive notification when it is in background. 在日志中,我能够看到为我的设备生成令牌,当我向令牌应用程序发送通知时,它在后台时没有收到通知。

But when i launch my app it calls applicationReceivedRemoteMessage: and i can see displed alert. 但是,当我启动我的应用程序时,它调用applicationReceivedRemoteMessage:我可以看到已发送的警报。

What could be the problem please help and thanks in advance! 可能有什么问题请提前帮助和谢谢!

The reason this happened to my project is because I'm using the same device token generated with my development db... turns out I need to delete and reinstall the app on my phone and register for notification to get new device token and generate new FCM registration id .. that works and I successfully received my notifications. 我的项目发生这种情况的原因是因为我使用了与我的开发数据库生成的相同设备令牌 ...结果我需要删除并重新安装我的手机上的应用程序并注册通知以获取新的设备令牌并生成新的FCM注册ID ..有效,我成功收到了我的通知。

Hope this helps. 希望这可以帮助。

When your APP enter background the notification message will send by Apple APNS service, so I think your .cer is wrong; 当您的APP进入后台时,Apple APNS服务会发送通知消息,所以我认为您的.cer是错误的; Apple have two .cer to push notification in coding/AppStore, if your APP not enter AppStore, try to use developerment .cer to do it. Apple有两个.cer在编码/ AppStore中推送通知,如果您的APP没有进入AppStore,请尝试使用developerment .cer来执行此操作。

My English is bad but may helpful to you! 我的英语不好但可能对你有帮助!

====edit==== try this? ====编辑====试试这个?

NSString *pushToken = [[[[deviceToken description]

                         stringByReplacingOccurrencesOfString:@"<" withString:@""]
                        stringByReplacingOccurrencesOfString:@">" withString:@""]
                       stringByReplacingOccurrencesOfString:@" " withString:@""];

I fixed this problem by enabling push notification capability in XCODE 8.1 我通过在XCODE 8.1中启用推送通知功能来解决此问题

Click on: 点击:

.xcodeproj -> Capabilities -> Enable Push Notification .xcodeproj - >功能 - >启用推送通知

and I have recreated provisioning profile. 我已经重新创建了配置文件。

Resolve this issue by turning on Push Notifications. 通过启用推送通知解决此问题。

Your Project -> capabilities -> turn on Push Notifications 您的项目 - >功能 - >启用推送通知

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在IOS 10 swift 3中未收到FCM通知 - FCM notification not receiving in IOS 10 swift 3 IOS 未通过 fcm 接收 Firebase 通知,而仅在 ANDROID 上接收 - IOS not receiving firebase notification via fcm but only on ANDROID Flutter FCM 推送通知未在 IOS 上接收到 firebase_messaging:^9.1.3 - Flutter FCM push notification not receiving on IOS with firebase_messaging: ^9.1.3 FCM 通知未收到 iOS - FCM Notifications not receiving iOS FCM iOS项目未收到通知-FCM控制台显示成功,但设备未收到 - FCM iOS project not receiving Notification - FCM console shows success but device does not receive 如果服务器端使用FCM发送通知,则必须在iOS客户端应用中使用FCM接收远程通知吗 - Is it mandatory to use FCM in iOS Client app for receiving remote notification if the server side uses FCM for sending notifications FCM + iOS + 通知扩展 - FCM + iOS + Notification Extension 针对ios的FCM自定义通知 - FCM custom notification for ios 在从FCM接收到iOS 12上的远程推送通知时播放自定义声音 - Playing a custom sound on receiving a remote push notification on iOS 12 from FCM 如果将“数据”(但“通知”工作)有效负载发送到iOS中的GCM / FCM,则不会收到推送通知didReceiveRemoteNotification - Not receiving push notifications if sending “data” (but “notification” works) payloads to GCM/FCM in iOS didReceiveRemoteNotification
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM