2017-02-15 12 views
0

Это мои настройки:Почему я не получаю баннер и фоновый режим нажимные notiifications при получении сообщения на консоли ios10.2

project settings

и

Project settings2

Это мой appDelegate

#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 
#endif 
//#import "FIRMessaging.h" 
//#define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v) ([[[UIDevice  currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) 
@import UIKit; 
@import Firebase; 
@import FirebaseMessaging; 
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 
#endif 
@interface AppDelegate() 
{ 
NSTimer *timer1; 
} 
@end 
// 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 { 

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].delegate = self; 
     // For iOS 10 data message (sent via FCM) 
     [FIRMessaging messaging].remoteMessageDelegate = self; 
#endif 
    } 

    [[UIApplication sharedApplication] registerForRemoteNotifications]; 
    // [END register_for_notifications] 
} 

    [FIRApp configure]; 
..../ 

плюс все это приложение делегат вызова поддерживает

 - (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. 
    // if (userInfo[kGCMMessageIDKey]) { 
//  NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]); 
//} 

// Print full message. 
    NSLog(@"%@", userInfo); 
} 
- (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. 
if (userInfo[kGCMMessageIDKey]) { 
    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]); 
} 

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

completionHandler(UIBackgroundFetchResultNewData); 
} 
// [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 { 
// Print message ID. 
NSDictionary *userInfo = notification.request.content.userInfo; 
if (userInfo[kGCMMessageIDKey]) { 
    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]); 
} 

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

// Change this to your preferred presentation option 
completionHandler(UNNotificationPresentationOptionNone); 
} 

    // 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: %@", userInfo[kGCMMessageIDKey]); 
    } 

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

    completionHandler(); 
    } 
    #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 
    NSLog(@"%@", remoteMessage.appData); 
    } 
    #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); 

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

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

    // With swizzling disabled you must set the APNs token here. 
[[FIRInstanceID instanceID] setAPNSToken:deviceToken  type:FIRInstanceIDAPNSTokenTypeSandbox]; 
} 

// [START connect_on_active] 
- (void)applicationDidBecomeActive:(UIApplication *)application { 
[self connectToFcm]; 
    } 
    // [END connect_on_active] 

    // [START disconnect_from_fcm] 
    - (void)applicationDidEnterBackground:(UIApplication *)application { 
    [[FIRMessaging messaging] disconnect]; 
    NSLog(@"Disconnected from FCM"); 
    } 
    // [END disconnect_from_fcm] 

Я не могу получить баннеры и уведомления в фоновом режиме, хотя я получаю сообщение в консоли, например (- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage срабатывает).

Звуков нет, и все профили обеспечения выполняются на всякий случай.

+0

Никто не имеет ответа на этот вопрос ... Im тупик потерян, я искал все соответствующие темы, делал все трюки, но все еще в ios10.2. Я не получаю уведомление, когда приложение в фоновом режиме или закрыто, ни баннер, когда приложение на переднем плане ... все, что я могу сделать, это показать окно предупреждения, когда сообщение появляется на консоли ... у кого-нибудь есть идея по этому поводу. Пожалуйста, помогите – user3585096

+0

Вы проверили, ответ успеха от 'applicationDidBecomeActive' 'connectToFcm'? – user3589771

+0

Да, пользователь3585096, я подключаюсь к FCM, и я получаю токен ... – user3585096

ответ

0

ОК решил это. Вам необходимо установить идентификатор приложения на веб-сайте разработчика Apple и включить push-уведомления как для разработки, так и для распространения (не подделывать идентификатор пакета не должен совпадать с идентификатором пакета на Xcode). После этого вам нужно создать профиль подготовки для этого Идентификатор приложения и установите его в свой mac.Last, но не в последнюю очередь вам нужно поставить в консоль Firebase файл p12, созданный из доступа к цепочке ключей. В консоли firebase у вас есть серая шестерня рядом с обзором. Вы выбираете эту вкладку, а затем вкладку облачных сообщений, и вы загружаете файл сертификата p12, сгенерированный в доступе к цепочке ключей, когда вы расширяете сертификацию push-уведомления и экспортируете файл p12. Вам нужно ввести пароль и загрузить его в firebase.

+0

Достаточно смешно после устранения проблемы в режиме разработки, когда я выпустил обновление приложение перестало работать там ... Еще один кошмар включен! – user3585096

+0

Опубликован следующий вопрос три недели назад, так как push-уведомления теперь работают только в dev elopment mode, а не в производстве ..... http: //stackoverflow.com/questions/43306068/im-not-getting-push-notifications-in-production-in-ios-10 – user3585096

0

Перед операцией if вам нужно позвонить [FIRApp configure]!

+0

Я боюсь, что я просто переехал [FIRApp configure] в начале didFinishLaunchingWithOptions, но все тот же ... – user3585096

+0

на самом деле просто протестировал на моем iPhone 5,2 пример обмена сообщениями firebase, и он тоже делает то же самое ... получение на консоли no banner no background notification. – user3585096