【问题标题】:"Onesignal for Voip push" and "Firebase Cloud Messaging" don't work together“Onesignal for Voip push”和“Firebase Cloud Messaging”不能一起使用
【发布时间】:2019-06-26 15:32:38
【问题描述】:

我正在集成通过更新“实时数据库”触发的“Firebase 云消息传递”,在与用于向 IOS 设备发送 Voip 推送通知的 One Signal 集成之前工作正常。 用于发送 Voip 推送通知的一个 Signal 运行良好。

有谁知道我的代码发生了什么,如果您能在下面更正我的代码,将对我非常有帮助(即使只是建议,教如何解决问题也是很大的帮助)。

已经尝试使用不带 Firebase 的 One Signal 发送常规推送通知和 Voip 推送通知,但 One Signal 技术支持提到“我们不建议将同一个应用程序用于 voip 和常规推送。”

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    // PushKit
    let registry = PKPushRegistry(queue: nil)
    registry.delegate = self
    registry.desiredPushTypes = [PKPushType.voIP]

    //  Converted to Swift 4 by Swiftify v4.1.6781 - https://objectivec2swift.com/
    FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)


    SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)

    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: {_, _ in })
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }



    let token = Messaging.messaging().fcmToken

    UserDefaults.standard.set(token, forKey: "FCM_TOKEN")
    print("Firebase registration token: \(token)")

    Messaging.messaging().delegate = self

    application.registerForRemoteNotifications()
    Messaging.messaging().isAutoInitEnabled = true

    let onesignalInitSettings = [kOSSettingsKeyAutoPrompt: false]


    OneSignal.initWithLaunchOptions(launchOptions,
                                    appId: "d1194195*******************5d",
                                    handleNotificationAction: nil,
                                    settings: onesignalInitSettings)


    OneSignal.inFocusDisplayType = OSNotificationDisplayType.notification;

    // Recommend moving the below line to prompt for push after informing the user about
    //   how your app will use them.
    OneSignal.promptForPushNotifications(userResponse: { accepted in
        print("User accepted notifications: \(accepted)")
    })


    print("===================================")
    OneSignal.postNotification(["contents": ["en": "Test Message"], "include_player_ids": ["9c64*****************0a54"]])

    return true
}

// Register for VoIP notifications


// Handle updated push credentials
func pushRegistry(registry: PKPushRegistry!, didUpdatePushCredentials credentials: PKPushCredentials!, forType type: String!) {
    // Register VoIP push token (a property of PKPushCredentials) with server
}



func application(application: UIApplication,
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken
    print("sdfksjkjfksajkdnslfs")
}


func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {



    // TODO: If necessary send token to application server.
    // Note: This callback is fired at each app startup and whenever a new token is generated.
}


func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("Received data message: \(remoteMessage.appData)")
}

//  Converted to Swift 4 by Swiftify v4.1.6781 - https://objectivec2swift.com/
func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    let handled: Bool = FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplicationOpenURLOptionsKey.annotation])
    // Add any custom logic here.
    return handled
}




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 invalidate graphics rendering callbacks. 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 active 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, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    return SDKApplicationDelegate.shared.application(application,
                                                     open: url,
                                                     sourceApplication: sourceApplication,
                                                     annotation: annotation)
}


func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {

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

    // Print full message.
    print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

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

    // Print full message.
    print(userInfo)

    completionHandler(UIBackgroundFetchResult.newData)
}


func providerDidReset(_ provider: CXProvider) {
}

func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {
    action.fulfill()
}

func provider(_ provider: CXProvider, perform action: CXEndCallAction) {
    action.fulfill()
}


func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) {
    print(pushCredentials.token.map { String(format: "%02.2hhx", $0) }.joined())




}



func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType, completion: @escaping () -> Void) {

    print("====Callkit====")

    let config = CXProviderConfiguration(localizedName: "My App")
    config.ringtoneSound = "ringtone.caf"
    config.includesCallsInRecents = false;
    config.supportsVideo = true;
    let provider = CXProvider(configuration: config)
    provider.setDelegate(self, queue: nil)
    let update = CXCallUpdate()


    update.remoteHandle = CXHandle(type: .generic, value: "Pete Za")
    update.hasVideo = true
    provider.reportNewIncomingCall(with: UUID(), update: update, completion: { error in })
}



 }
 @available(iOS 10, *)
     extension AppDelegate : UNUserNotificationCenterDelegate {

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo
    let message = "yap"

    if let messageID = userInfo["gcm.message_id"] {
        print("Message ID: \(messageID)")

        completionHandler([.alert, .sound])

    }

    print(userInfo)



}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    if let messageID = userInfo["gcm.message_id"] {
        print("Message ID: \(messageID)")

    }

    print(userInfo)


     }
}

并在集成 One Signal 时添加了以下 UNNotificationServiceExtension

class NotificationService: UNNotificationServiceExtension {

var contentHandler: ((UNNotificationContent) -> Void)?
var receivedRequest: UNNotificationRequest!
var bestAttemptContent: UNMutableNotificationContent?

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
    self.receivedRequest = request;
    self.contentHandler = contentHandler
    bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

    if let bestAttemptContent = bestAttemptContent {
        OneSignal.didReceiveNotificationExtensionRequest(self.receivedRequest, with: self.bestAttemptContent)
        contentHandler(bestAttemptContent)
    }
}

override func serviceExtensionTimeWillExpire() {
    // Called just before the extension will be terminated by the system.
    // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
    if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
        OneSignal.serviceExtensionTimeWillExpireRequest(self.receivedRequest, with: self.bestAttemptContent)
        contentHandler(bestAttemptContent)
       }
    }
}

【问题讨论】:

  • 您是否检查过推送令牌是否发送到 fcm 服务器?

标签: ios swift firebase google-cloud-messaging onesignal


【解决方案1】:

你应该使用content-available标志

关于 Firebase 文档,您必须以某种方式传递 content_available 参数。它可能对您的情况有所帮助。

https://firebase.google.com/docs/cloud-messaging/http-server-ref

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 2022-06-25
    • 2020-07-31
    相关资源
    最近更新 更多