Xcode 8.1 推送通知在 swift 2.3 中与 firebase 集成没有得到?

2023-12-21

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

     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)
    }
}

既然你要求我另一个帖子的评论区,我将发布此工作代码集,其配置与您提到的相同:

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 #############################################
}

有效负载格式:

[aps: {
    alert =     {
        body = "Some message.";
        title = "Some title";
     };
     category = " ";
 }, Name: ios, gcm.message_id: 0:1474608925388897%17bce75117bc5555]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Xcode 8.1 推送通知在 swift 2.3 中与 firebase 集成没有得到? 的相关文章

  • RemoteIO 音频单元播放回调中的 AudioBufferList 内容

    我想 拦截 音频数据传送到 iOS 设备扬声器的过程 我相信这可以使用 RemoteIO 音频单元和回调来完成 在下面的playbackCallback中 ioData实际上包含任何音频数据吗 static OSStatus playbac
  • 苹果推送通知在生产中不起作用

    我们完全陷入困境 请帮忙 我和我的团队制作了一个 iPhone 应用程序 这是我们第一次在 iOS 上尝试 一切都很好 直到我们提交应用程序并在应用程序商店上可用为止 推送通知服务无法正常工作 我在网上搜索并尝试根据人们的建议仔细检查我们的
  • 仅将 UIImage 移动到另一个 UIImage 内部

    I have an UIImage which is shown in an UIImageView I also have another image in an UIImageView which lays above the firs
  • 检索 iPhone 中的 Outlook 联系人

    我想通过应用程序导入所有 Outlook 联系人 有什么办法可以做到这一点吗 请告诉我 您可以通过实施 Microsoft Exchange 服务器协议来实现此目的 微软MSDN http msdn microsoft com en us
  • 由于 Chrome 修订,Firebase puppeteer PDF 功能超时

    我有一个 Firebase 函数来创建 PDF 文件 最近 由于 Chrome 修订版 而超时 我既不明白错误消息 也不明白出了什么问题 当我在 MacOS 下将其本地部署时 该功能有效 TimeoutError Timed out aft
  • 奇怪的 UITableView 插入/删除行动画

    在带有动画 UITableView RowAnimationTop 的 UITableView 中插入 删除 UITableViewCell 时 我看到了奇怪的效果 当要插入的单元格比上面的单元格大得多时 就会发生动画故障 显示模拟器中的故
  • 具有自动布局的 UITableViewCell 中的 UILabel 高度错误

    我有一个UITableView单元格的固定高度为 100 点 这些单元格是在 xib 文件中创建的 该文件使用 3 个约束来固定UILabel到单元格的左 右和上边缘contentView 标签的垂直拥抱优先级设置为 1000 因为我希望单
  • Firebase Analytics 禁用受众国家/地区跟踪

    我正在开发一个严格不允许位置跟踪的应用程序 我想使用 Firebase Analytic 的其他功能 例如 PageTransitions 和 Crashalitics 但如果我无法禁用受众位置跟踪 我就无法使用其中任何功能 这是我在 An
  • 获取对 iOS 应用程序中最顶层视图/窗口的引用

    我正在创建一个可重用的框架 用于在 iOS 应用程序中显示通知 我希望将通知视图添加到应用程序中其他所有内容的顶部 有点像 UIAlertView 当我初始化监听 NSNotification 事件并添加视图作为响应的管理器时 我需要获取对
  • 使用 iPhone 摄像头检测心率 [重复]

    这个问题在这里已经有答案了 可能的重复 使用摄像头检测心率 https stackoverflow com questions 9274027 detecting heart rate using the camera 我正在研究 iOS
  • Swift 闭包作为 AnyObject

    我尝试使用这个方法 class addMethod 在 Obj c 中使用如下 class addMethod self class selector eventHandler imp implementationWithBlock han
  • 如何自动缩放mapView以显示叠加层

    我可以在 mapView 上绘制多边形 但是我需要找到多边形并手动缩放它 有没有办法自动执行此过程 例如调整中心多边形 我浏览过互联网并阅读了一些相关文章 其中大多数都是基于折线和点的 任何形式的帮助将不胜感激 因为我正在寻找解决方案一段时
  • ViewWillAppear 没有被 UISplitViewController 调用

    背景和目标 我有一个基于 UISplitViewController 的 iPad 应用程序 到目前为止它支持 4 个方向 但现在我想将其锁定为仅横向 我变了shouldAutorotateToInterfaceOrientation左视图
  • firebase 和 firebase-admin npm 模块有什么区别?

    我想使用 Firebase 身份验证 数据库和存储 构建 Node js Web 应用程序 但我对应该使用哪个模块感到困惑 firebase or firebase 管理员 或两者 管理 SDK 运行您的代码管理权限 https fireb
  • 使用 NSURLSessionDataTask 显示文件下载进度

    我想显示特定文件的文件下载进度 收到了多少字节 它与 NSURLSessionDownloadTask 配合得很好 我的问题是我想用 NSURLSessionDataTask 实现同样的效果 以下是将文件接收到 NSData 并写入文档文件
  • 尝试复制文件时出错

    我正在尝试使用 NSFileManager 将临时文件复制到另一个位置 但是它失败并抱怨其中一个文件不存在 Copy temp file NSError error BOOL exists fileManager fileExistsAtP
  • -[EAGLContext renderbufferStorage:fromDrawable:] 第二次失败?

    我正在开发一个 iOS openGL ES 应用程序 我正在做通常的 EAGLView ES2Render 的事情 启动时 使用以下代码成功创建 frambuffer BOOL createFramebuffers EAGLContext
  • 在 iOS 11 中创建 Gif 图像颜色贴图

    最近 我在创建 Gif 时遇到了一个问题 如果它太大 颜色就会丢失 然而 感谢 SO 的帮助 有人能够帮助我找到解决方法并创建我自己的颜色图 上一个问题在这里 保存动画 Gif 时 iOS 颜色不正确 https stackoverflow
  • 是什么导致了这个 iPhone 崩溃日志?

    我有点卡住了 需要解决这个问题 因为我的一个应用程序出现了随机崩溃 而这些崩溃并不总是能够重现 这是崩溃日志之一 Incident Identifier 59865612 9F00 44EA 9474 2BF607AD662E CrashR
  • 用 UIView 像翻书一样翻页?

    我正在尝试在之间切换UIViews让它看起来就像你正在翻书的一页 The UIViewAnimationTransitionCurlUp如果我能让它向左或向右卷曲 那就非常接近了 这可能吗 我尝试过使用CATRansition但没有一种动画

随机推荐