Xcode 8.1推送通知在swift 2.3与firebase集成没有得到? [英] Xcode 8.1 Push Notifications in swift 2.3 with firebase integration not getting?

查看:238
本文介绍了Xcode 8.1推送通知在swift 2.3与firebase集成没有得到?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Xcode 8.1& swift 2.3这里我正在使用firebase集成获取推送notification.I不知道为什么我没有得到通知..
我的代码:

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


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

//对于iOS 10显示通知(通过APNS发送)
UNUserNotificationCenter。 currentNotificationCenter()。delegate = self
//对于iOS 10数据消息(通过FCM发送)
FIRMessaging.messaging()。remoteMessageDelegate = self
application.registerForRemoteNotifications()

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

application.registerForRemoteNotifications()
FIRApp.configure()

//为InstanceID令牌刷新回调添加观察者。
if #available(iOS 10.0,*){
NSNotificationCenter.defaultCenter()。addObserver(self,
selector:#selector(self.tokenRefreshNotification),
name:kFIRInstanceIDTokenRefreshNotification,
object:nil)
} else {
//早期版本的后退
}
返回true
}

func application(application:UIApplication,didReceiveRemoteNotification userInfo:[NSObject:AnyObject],
fetchCompletionHandler completionHandler:(UIBackgroundFetchResult) - > Void) b $ b}

func应用程序(应用程序:UIApplication,didRegisterUserNotificationSettings notificationSettings:U IUserNotificationSettings)
{
application.registerForRemoteNotifications()

$ b}

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

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

// Tricky line
FIRInstanceID.instanceID()。setAPNSToken(deviceToken,type:FIRInstanceIDAPNSTokenType.Unknown)
print(Device Token:,tokenString)

$ b func application应用程序:UIApplication,didFailToRegisterForRemoteNotificationsWithError错误:错误){
//将错误打印到控制台(您应该提醒用户注册失败)
print (APN注册失败:\(错误))

$ b $可用(iOS 10.0,*)
func tokenRefreshNotification(通知:UNUserNotificationCenter){
如果让refreshedToken = FIRInstanceID.instanceID()。token(){
print(InstanceID token:\(refreshedToken))
let deviceFCMToken:String = refreshedToken
NSUserDefaults.standardUserDefaults .setObject(deviceFCMToken,forKey:FCMToken)
NSUserDefaults.standardUserDefaults()。setBool(true,forKey:isFCMTokenAvailable)
//UIApplication.sharedApplication()。registerForRemoteNotifications()
}

//连接到FCM,因为在拥有令牌之前尝试连接可能失败。
connectToFcm()
}
func connectToFcm()
{
FIRMessaging.messaging()。connectWithCompletion {(error)in
if(error!=无)
{
print(Unable to connect with FCM。\(error))
} else {
print(Connected to FCM。)
}
}
}


扩展AppDelegate:FIRMessagingDelegate
{
//在iOS 10设备上接收数据消息。
func applicationReceivedRemoteMessage(remoteMessage:FIRMessagingRemoteMessage)
print(%@,remoteMessage.appData)
}
}


解决方案

由于您在另一个线程的评论部分请求了我 ,我发布这个工作集的代码与您提到的相同的配置:

$ p $ import UserNotifications

@UIApplicationMain
$ b $ class AppDelegate:UIResponder,UIApplicationDelegate,CLLocationManagerDelegate,UNUserNotificationCenterDelegate {
var window:UIWindow?

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

// ############## FIREBASE ##################

registerForPushNotifications(应用程序)
FIRApp.configure()
//为InstanceID令牌刷新回调添加观察者。
NSNotificationCenter
.defaultCenter()
.addObserver(self,selector:#selector(AppDelegate.tokenRefreshNotification),
name:kFIRInstanceIDTokenRefreshNotification,object:nil)

// ############ FIREBASE END ################

return true
}


// MARK: - FIREBASE START

// ###################### ################## FIREBASE START ############################## #############
$ b $ func registerForPushNotifications(application:UIApplication){

if #available(iOS 10.0,*){
)UNUserNotificationCenter.currentNotificationCenter()。delegate = self
如果(授予)UNUserNotificationCenter.currentNotificationCenter()。requestAuthorizationWithOptions([。Badge,.Sound,.Alert],completionHandler:{(granted,error)
{
UIApplication.s ()
}
else {
//做不成功的事情...
}
})
}

else {//如果用户不在iOS 10上,使用我们已经使用过的旧方法
let notificationSettings = UIUserNotificationSettings(
forTypes:[.Badge,.Sound,.Alert] ,类别:无)
application.registerUserNotificationSettings(notificationSettings)
}
}


$ b func应用程序(application:UIApplication,didRegisterUserNotificationSettings notificationSettings :UIUserNotificationSettings){
如果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(格式:%02.2hhx,参数:[tokenChars [i]])
}

// Tricky line
FIRInstanceID.instanceID()。setAPNSToken(deviceToken,type: FIRInstanceIDAPNSTokenType.Sandbox)
print(Device Token:,tokenString)
print(Firebase Token:,FIRInstanceID.instanceID()。token())
}

// [START receive_message]


@available(iOS 10.0,*)
func userNotificationCenter(中心:UNUserNotificationCenter,willPresentNotification通知:UNNotification,withCompletionHandler completionHandler :( UNNotificationPresentationOptions ) - >无效){
//处理通知
//使用这个地方来处理


$ b @available(iOS 10.0,*)
func userNotificationCenter(center:UNUserNotificationCenter,didReceiveNotificationResponse response:UNNotificationResponse,withCompletionHandler completionHandler:() - > Void){
//处理通知
//使用这个地方处理通知
应用程序(应用程序:UIApplication,didReceiveRemoteNotification,userInfo:[NSObject:AnyObject],
fetchCompletionHandler completionHandler:(UIBackgroundFetchResult) - >无效){b $ print $ {
}



print(userInfo)
}

// [END receive_message]

// [START refresh_token]
func tokenRefreshNotification(通知:NSNotification){
如果让refreshedToken = FIRInstanceID.instanceID()。token(){
print(I nstanceID标记:\(refreshedToken))
}

//连接到FCM,因为连接可能在拥有令牌之前尝试失败。
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()
UIApplication.sharedApplication()。applicationIconBadgeNumber = 0
//FBSDKAppEvents.activateApp()
}

// [START disconnect_from_fcm]
func applicationDidEnterBackground(application:UIApplication){
//FIRMessaging.messaging()。disconnect()
print(与FCM断开连接)
}
// [END disconnect_from_fcm]


// ###################################### FIREBASE ##### #####################################
// ####### ################################# 结束 ################ #############################
}


 [aps: {
alert = {
body =某条消息。;
title =一些标题;
};
category =;
},名称:ios,gcm.message_id:0:1474608925388897%17bce75117bc5555]


I am working with Xcode 8.1 & swift 2.3 here I am using firebase integration for getting push notifications.I don't know why i am not getting notifications.. My code:

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


            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
                 application.registerForRemoteNotifications()

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

            application.registerForRemoteNotifications()
            FIRApp.configure()

            // Add observer for InstanceID token refresh callback.
            if #available(iOS 10.0, *) {
                NSNotificationCenter.defaultCenter().addObserver(self,
                                                                 selector: #selector(self.tokenRefreshNotification),
                                                                 name: kFIRInstanceIDTokenRefreshNotification,
                                                                 object: nil)
            } else {
                // Fallback on earlier versions
            }
    return true
    }

  func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                     fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

        FIRMessaging.messaging().appDidReceiveMessage(userInfo)
}

 func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings)
    {
        application.registerForRemoteNotifications()


    }

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

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

        //Tricky line
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)
        print("Device Token:", tokenString)

    }
    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        // Print the error to console (you should alert the user that registration failed)
        print("APNs registration failed: \(error)")
    }

    @available(iOS 10.0, *)
    func tokenRefreshNotification(notification: UNUserNotificationCenter) {
        if let refreshedToken = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")
            let deviceFCMToken: String = refreshedToken
            NSUserDefaults.standardUserDefaults().setObject(deviceFCMToken, forKey: "FCMToken")
            NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isFCMTokenAvailable")
             //UIApplication.sharedApplication().registerForRemoteNotifications()
        }

        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }
    func connectToFcm()
    {
        FIRMessaging.messaging().connectWithCompletion { (error) in
            if (error != nil)
            {
                print("Unable to connect with FCM. \(error)")
            } else {
                print("Connected to FCM.")
            }
        }
    }


extension AppDelegate : FIRMessagingDelegate
{
    // Receive data message on iOS 10 devices.
    func applicationReceivedRemoteMessage(remoteMessage: FIRMessagingRemoteMessage)
    {

        print("%@", remoteMessage.appData)
    }
}

解决方案

Since you requested me on another thread's comment section, I am posting this working set of code with the same configuration you have mentioned:

import UserNotifications

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate,CLLocationManagerDelegate, UNUserNotificationCenterDelegate {
    var window: UIWindow?

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

        //############## FIREBASE ##################

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

        //############ FIREBASE END ################  

        return true
    }


    //MARK: - FIREBASE START

    //######################################## FIREBASE START ###########################################

    func registerForPushNotifications(application: UIApplication) {

        if #available(iOS 10.0, *){
            UNUserNotificationCenter.currentNotificationCenter().delegate = self
            UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert], completionHandler: {(granted, error) in
                if (granted)
                {
                    UIApplication.sharedApplication().registerForRemoteNotifications()
                }
                else{
                    //Do stuff if unsuccessful...
                }
            })
        }

        else{ //If user is not on iOS 10 use the old methods we've been using
            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]])
        }

        //Tricky line
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox)
        print("Device Token:", tokenString)
        print("Firebase Token:",FIRInstanceID.instanceID().token())
    }

    // [START receive_message]


    @available(iOS 10.0, *)
    func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
        //Handle the notification
        //Use this place to handle
    }


    @available(iOS 10.0, *)
    func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
        //Handle the notification
        //Use this place to handle the notification
        print(response)
    }

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                     fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

        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()
        UIApplication.sharedApplication().applicationIconBadgeNumber = 0
        //FBSDKAppEvents.activateApp()
    }

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


    //###################################### FIREBASE ##########################################
    //######################################## END #############################################
}

Payload Format:

[aps: {
    alert =     {
        body = "Some message.";
        title = "Some title";
     };
     category = " ";
 }, Name: ios, gcm.message_id: 0:1474608925388897%17bce75117bc5555]

这篇关于Xcode 8.1推送通知在swift 2.3与firebase集成没有得到?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆