"Onesignal对VoIP推送的支持"和"Firebase Cloud Messaging"不兼容。

5
我正在集成“Firebase Cloud Messaging”,通过“实时数据库”触发更新,这一直很好,直到与One Signal集成为止。 我们使用One Signal向iOS设备发送Voip推送通知。 One Signal 用于发送Voip推送通知非常完美。
请问有人知道我的代码出了什么问题吗?如果您能更正下面的代码甚至只是提供建议和教学如何解决这个问题将对我非常有帮助。
已尝试使用不带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 服务器了吗? - Tibin Thomas
1个回答

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接