2016-09-27 186 views
4

我很努力地显示我从FCM通知控制台发送给我的设备的推送通知。我可以看到设备正在接收的通知,因为我可以看到我发送“test8”ios10,Swift 3和Firebase推送通知(FCM)

Connected to FCM. 
%@ [AnyHashable("notification"): { 
    body = test8; 
    e = 1; 
}, 

消息但是,如果我的应用是在我没有得到通知显示在前台或后台没关系。

我在info.plist中添加了“所需的背景模式 - 应用程序下载内容以响应推送通知”。我的证书是正确的,我没有问题生成一个令牌。我的应用程序正在接收通知,但没有显示它们。

import UIKit 
import UserNotifications 
import Firebase 
import FirebaseInstanceID 
import FirebaseMessaging 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 

    var window: UIWindow? 

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

     // [START register_for_notifications] 
     if #available(iOS 10.0, *) { 
      let authOptions : UNAuthorizationOptions = [.Alert, .Badge, .Sound] 
      UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
       authOptions, 
       completionHandler: {_,_ in }) 

      // For iOS 10 display notification (sent via APNS) 
      UNUserNotificationCenter.currentNotificationCenter().delegate = self 
      // For iOS 10 data message (sent via FCM) 
      FIRMessaging.messaging().remoteMessageDelegate = self 

     } else { 
      let settings: UIUserNotificationSettings = 
       UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) 
      application.registerUserNotificationSettings(settings) 
      application.registerForRemoteNotifications() 
     } 

     application.registerForRemoteNotifications() 

     // [END register_for_notifications] 

     FIRApp.configure() 

     // Add observer for InstanceID token refresh callback. 
     NSNotificationCenter.defaultCenter().addObserver(self, 
                 selector: #selector(self.tokenRefreshNotification), 
                 name: kFIRInstanceIDTokenRefreshNotification, 
                 object: nil) 

     return true 
    } 

    // [START receive_message] 
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], 
        fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { 
     // 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. 
     print("Message ID: \(userInfo["gcm.message_id"]!)") 

     // Print full message. 
     print("%@", userInfo) 
    } 
    // [END receive_message] 

    // [START refresh_token] 
    func tokenRefreshNotification(notification: NSNotification) { 
     if let refreshedToken = FIRInstanceID.instanceID().token() { 
      print("InstanceID token: \(refreshedToken)") 
     } 

     // Connect to FCM since connection may have failed when attempted before having a token. 
     connectToFcm() 
    } 
    // [END refresh_token] 

    // [START connect_to_fcm] 
    func connectToFcm() { 
     FIRMessaging.messaging().connectWithCompletion { (error) in 
      if (error != nil) { 
       print("Unable to connect with FCM. \(error)") 
      } else { 
       print("Connected to FCM.") 
      } 
     } 
    } 
    // [END connect_to_fcm] 

    func applicationDidBecomeActive(application: UIApplication) { 
     connectToFcm() 
    } 

    // [START disconnect_from_fcm] 
    func applicationDidEnterBackground(application: UIApplication) { 
     FIRMessaging.messaging().disconnect() 
     print("Disconnected from FCM.") 
    } 
    // [END disconnect_from_fcm] 
} 

// [START ios_10_message_handling] 
@available(iOS 10, *) 
extension AppDelegate : UNUserNotificationCenterDelegate { 

    // Receive displayed notifications for iOS 10 devices. 
    func userNotificationCenter(center: UNUserNotificationCenter, 
           willPresentNotification notification: UNNotification, 
           withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) { 
     let userInfo = notification.request.content.userInfo 
     // Print message ID. 
     print("Message ID: \(userInfo["gcm.message_id"]!)") 
     // Print full message. 
     print("%@", userInfo) 
    } 
} 

extension AppDelegate : FIRMessagingDelegate { 
    // Receive data message on iOS 10 devices. 
    func applicationReceivedRemoteMessage(remoteMessage: FIRMessagingRemoteMessage) { 
     print("%@", remoteMessage.appData) 
    } 
} 
// [END ios_10_message_handling] 

我一直在尝试自己研究和解决这个问题,但我有问题。任何帮助或建议将不胜感激。

+0

难道ü解决问题乌尔,我不是在Xcode 8.1迅速2.3.since几天我从服务器端尝试我收到的,也当我送火力控制台我收到,请您及时收到通知你能帮我吗 。 –

回答

7

里面方法didRegisterForRemoteNotificationsWithDeviceToken,添加以下代码:

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("tokenString: \(tokenString)") 
} 

而且不要忘记启用推送通知能力

+0

我添加了以下内容,因为我使用的是swift语法,但它没有解决我遇到的问题。我很欣赏这个建议。 FUNC应用(_应用:UIApplication的, didRegisterForRemoteNotificationsWithDeviceToken deviceToken:数据){ FIRInstanceID.instanceID()setAPNSToken(deviceToken,类型:FIRInstanceIDAPNSTokenType.sandbox)。 } –

+1

@Paul_D此行添加到您的Info.plist文件: FirebaseAppDelegateProxyEnabled和将布尔值设置为NO –

+0

感谢您的帮助Gustavo。我仍在挣扎我收到以下错误... 无法获取APNS令牌Error Domain = com.firebase.iid Code = 1001“(null)”。我收到的通知只是不显示它们。我正在搜索谷歌,并尽我所能来解决这个问题。我知道我已经正确地将我的.p12认证上传到了项目设置下的Firebase控制台以及云下消息传递。推送通知和(背景模式 - >远程通知)都启用。 –

3

你需要移动

application.registerForRemoteNotifications() 

它不应该是别人的内部。

// [START register_for_notifications] 
    if #available(iOS 10.0, *) { 
     let authOptions : UNAuthorizationOptions = [.Alert, .Badge, .Sound] 
     UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
      authOptions, 
      completionHandler: {_,_ in }) 

     // For iOS 10 display notification (sent via APNS) 
     UNUserNotificationCenter.currentNotificationCenter().delegate = self 
     // For iOS 10 data message (sent via FCM) 
     FIRMessaging.messaging().remoteMessageDelegate = self 

    } else { 
     let settings: UIUserNotificationSettings = 
      UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) 
     application.registerUserNotificationSettings(settings)    
    } 

application.registerForRemoteNotifications() 

See following commit in Firebase

+0

是的,这解决了我的问题!原始的源代码必须更新! – Alexey

+0

谢谢,我也解决了我的问题。不过,你应该更新你的代码swift 3. –

2

对我来说是缺少entitlements文件,所以在项目的Capabilities,你必须点击修复问题。 Xcode会为你设置文件。

enter image description here

+0

我认为这将是大多数Xcode 8+用户的修补程序!干杯 – Josh