0

Так что я только что реализовал (хорошо попытался) Push Notifications для моего приложения. Я отсортировал все сертификаты и все работает в Xcode. Я загрузил файл .p12 в Firebase в раздел разработки и даже загрузил профиль подготовки и переустановил его в свой проект.Уведомления не отображаются с Firebase

Это код в моем AppDelegate.swift файле

Обновленный код:

import UIKit 
import Firebase 
import FirebaseMessaging 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 

    var window: UIWindow? 
    var storyboard: UIStoryboard? 

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
     FIRApp.configure() 

     // Override point for customization after application launch. 

     self.storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) 
     let currentUser = FIRAuth.auth()?.currentUser 
     if currentUser != nil 
     { 
      self.window?.rootViewController = self.storyboard?.instantiateViewControllerWithIdentifier("tBVC") 
     } 
     else 
     { 
      self.window?.rootViewController = self.storyboard?.instantiateViewControllerWithIdentifier("loginScreen") 
     } 

     return true 
    } 

    func registerForPushNotifications(application: UIApplication) { 
     let notificationSettings = UIUserNotificationSettings(
      forTypes: [.Badge, .Sound, .Alert], categories: nil) 
     application.registerUserNotificationSettings(notificationSettings) 
    } 

    func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { 
     if notificationSettings.types != .None { 
      application.registerForRemoteNotifications() 
     } 
    } 

    func applicationWillResignActive(application: UIApplication) { 
     // 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. 
    } 

    func applicationDidEnterBackground(application: UIApplication) { 
     // 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. 
    } 

    func applicationWillEnterForeground(application: UIApplication) { 
     // 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. 
    } 

    func applicationDidBecomeActive(application: UIApplication) { 
     // 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. 
    } 

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

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { 

     print(userInfo) 
     print("MessageID: \(userInfo["gcm_message_id"]!)") 
     // 
    } 


} 

Когда приложение не работает в фоновом режиме, не отображает уведомления, даже если мое устройство не заблокировано до сих пор ничего. Появилось предупреждение о том, было ли у приложения разрешение на отправку уведомлений, и я сказал «да».

Я следовал за этим tutorial

Любая идея, почему не отображаются мои уведомления? В Firebase консоли это говорит о том, что статус уведомления «Завершено»

EDIT - Добавлен образ моих возможностей в Xcode enter image description here

+0

Вы отключили swizzling? –

+0

Извините, что это такое – Konsy

+0

Это код, который автоматически связывает токен вашего экземпляра вашего приложения с токеном APN вашего приложения от Apple. По умолчанию это маловероятно. –

ответ

1

Я выяснил причину, почему это так! Как сказал @Collinizer, есть проблемы с Apple и там APNS, но сейчас все работает! Я добавил push-уведомления при использовании OneSignal, и они работают как сон!

Спасибо всем, что помогло :)

0

вам нужно настроить набор из APNS устройства маркер, который является имеет решающее значение для push-уведомлений с Firebase Cloud Messaging (FCM).

Сначала давайте немного поднимемся и начнем с того, что увидим, можем ли мы хотя бы добиться успеха.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 

FIRApp.configure() 
return true 
} 

func registerForPushNotifications(application: UIApplication) { 
    let notificationSettings = UIUserNotificationSettings(
     forTypes: [.Badge, .Sound, .Alert], categories: nil) 
    application.registerUserNotificationSettings(notificationSettings) 
} 

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { 
    if notificationSettings.types != .None { 
     application.registerForRemoteNotifications() 
    } 
} 


func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { 
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes) 
var tokenString = "" 

for i in 0..<deviceToken.length { 
    tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]]) 
} 


FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown) 
print("Device Token:", tokenString) 
} 
+0

Большое спасибо! done btw – Konsy

+0

и ... убедитесь, что Bundle ID - это то же самое, что вы установили в GoogleService-Info. и убедитесь, что они верны и соответствуют: http://i.stack.imgur.com/p5N2F.png. Цель - сначала проверить токены. – tymac

+0

Да, все правильно настроено в отношении сертификатов, и настройки моей панели firebase правильные. Весь мой проект вернулся к действительно старому (первая версия); что я просто потерял всю новую работу, даже несмотря на то, что она была сохранена ... – Konsy

Смежные вопросы