当我断开设备与 Xcode 的连接时,推送通知不起作用 [英] Push Notifications Are Not working When I disconnect my device from Xcode

查看:24
本文介绍了当我断开设备与 Xcode 的连接时,推送通知不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 swift 语言开发一个 IOS 应用程序.我已将基于 Firebase 的推送通知添加到我的项目中.当我的设备连接到 xcode 或在我的设备上调试我的应用程序时,它们可以正常工作.但是当我从 xcode 断开我的设备或者我使用应用程序而不调试推送通知时是行不通的.我正在寻找解决方案

I am Developing an IOS App using swift language. I have added Firebase based push notifications to my project. they works correctly when my device is attached to xcode or when i debug my app on my device. But when ever i disconnect my device from xcode or i use app without debugging push notification doesn't work. I am looking for a solution

我在应用程序委托文件中的代码

My code in App Delegate File

在 didFinishLaunchingWithOptions 函数中

In didFinishLaunchingWithOptions function

if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self

        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(options: authOptions,
                                                                completionHandler: { (bool, err) in

        })

    } else {

        let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)

    }

    application.registerForRemoteNotifications()
    UIApplication.shared.applicationIconBadgeNumber = 0

在 didregisterdevicewithtoken 函数中

in didregisterdevicewithtoken function

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("APNs token retrieved: \(deviceToken)")

    // With swizzling disabled you must set the APNs token here.
    if let refreshedToken = InstanceID.instanceID().token() {
        print("InstanceID token: \(refreshedToken)")

    }
    let tokenT = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    print(tokenT)
    guard let token = InstanceID.instanceID().token() else {return}
    AppDelegate.DEVICEID = token
    print(token)
    UserDefaults.standard.set(token, forKey: "token")

    connectToFCM()


}

并生成通知

 func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (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

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    if let msg = userInfo["desc"] as? String
    {
        let title = userInfo["noti_title"] as? String
        createNotification(message: msg, title: title ?? "" )

    }

    // Print full message.
    print(userInfo)

    completionHandler(UIBackgroundFetchResult.newData)
}


func createNotification(message: String, title: String) {

    let content = UNMutableNotificationContent()
    content.title =  title
    content.body = message


    let triger = UNTimeIntervalNotificationTrigger(timeInterval: 2, repeats: false )
    let request = UNNotificationRequest(identifier: "TextMessage", content: content, trigger: triger)



    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

UNUserNotificationCenterDelegate

UNUserNotificationCenterDelegate

extension AppDelegate : UNUserNotificationCenterDelegate {

// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    let userInfo = notification.request.content.userInfo

    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([.alert,.badge,.sound])
}


func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    let application = UIApplication.shared

    if(application.applicationState == .active){
        print("user tapped the notification bar when the app is in foreground")

        window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()

        //        let layout = UICollectionViewFlowLayout()
        window?.rootViewController = UINavigationController(rootViewController: NotificationViewController())


    }

    if(application.applicationState == .inactive)
    {
        print("user tapped the notification bar when the app is in background")
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()

        //        let layout = UICollectionViewFlowLayout()
        window?.rootViewController = UINavigationController(rootViewController: NotificationViewController())

    }

    /* Change root view controller to a specific viewcontroller */
    // let storyboard = UIStoryboard(name: "Main", bundle: nil)
    // let vc = storyboard.instantiateViewController(withIdentifier: "ViewControllerStoryboardID") as? ViewController
    // self.window?.rootViewController = vc

    completionHandler()
}

func connectToFCM()
{
    Messaging.messaging().shouldEstablishDirectChannel = true
}
func initializeNotificationServices() -> Void {
    let settings = UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil)
    UIApplication.shared.registerUserNotificationSettings(settings)

    // This is an asynchronous method to retrieve a Device Token
    // Callbacks are in AppDelegate.swift
    // Success = didRegisterForRemoteNotificationsWithDeviceToken
    // Fail = didFailToRegisterForRemoteNotificationsWithError
    UIApplication.shared.registerForRemoteNotifications()

推荐答案

我已经解决了这个问题.现在我在 firebase 控制台中添加了生产 Apn 证书并从 firebase 控制台中删除了开发 apn 证书.对于那些有同样问题的人,请从 apple.developers 生成你的生产应用程序,并在构建选项卡中将你的项目方案从调试更改为发布.

I have solved this problem. Now i have added production Apn certificate in firebase console and removed development apn certificate from firebase console. for those who had same issue please generate ur production apn from apple.developers and change your project scheme from debug to release in build tab.

这篇关于当我断开设备与 Xcode 的连接时,推送通知不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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