«Onesignal для Voip push» и «Firebase Cloud Messaging» не работают вместе - PullRequest
0 голосов
/ 02 февраля 2019

Я интегрирую этот «Firebase Cloud Messaging», вызванный обновлением в «базе данных реального времени», которая работала нормально, пока интеграция с One Signal не использовалась для отправки push-уведомлений Voip на устройства IOS.Один сигнал для отправки push-уведомлений Voip работает отлично.

Кто-нибудь знает, что произойдет с моим кодом, и было бы очень полезно для меня, если бы вы могли исправить мой код, приведенный ниже (даже единственное предложение, обучение тому, как решить эту проблему,также большая помощь).

уже пытались отправлять обычные push-уведомления и push-уведомления Voip, используя One Signal без Firebase, однако Техническая поддержка One Signal отметила, что «мы не рекомендуем использовать одно и то же приложение для voip и обычной push-рассылки».

 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 голосов
/ 21 марта 2019

Вы должны использовать content-available flag

Что касается документации Firebase, вы должны как-то передать параметр content_available.Это может помочь в вашем случае.

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

...