“ Onesignal for Voip push”和“ Firebase Cloud Messaging”不能同时使用

时间:2019-02-02 04:22:09

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

我正在集成通过在“实时数据库”中进行更新而触发的“ Firebase Cloud Messaging”,在与One Signal集成以将Voip推送通知发送到IOS设备之前,它一直运行良好。 发送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)


     }
}

,并且在集成一个信号时还添加了以下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)
       }
    }
}

1 个答案:

答案 0 :(得分:2)

您应该使用content-available标志

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

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