“用于Voip推送的Onesignal”和“Firebase云消息传递”不能一起使用

问题描述 投票:5回答:1

我正在集成通过“实时数据库”更新触发的“Firebase云消息传递”,该工作正常,直到与One Signal集成,用于向IOS设备发送Voip推送通知。发送Voip推送通知的One Signal工作正常。

有没有人知道我的代码会发生什么,如果你能纠正我的代码,对我来说会非常有帮助(即使只是建议,教导如何解决这些也是很大的帮助)。

已经尝试使用One Signal无Firebase发送常规推送通知和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)
       }
    }
}
ios swift firebase google-cloud-messaging onesignal
1个回答
2
投票

你应该使用content-available标志

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

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

© www.soinside.com 2019 - 2024. All rights reserved.