FCM Pu sh звук уведомления не работает IOS (возможно дублирование, но не работает никаких решений) - PullRequest
0 голосов
/ 09 июля 2020

pu sh уведомление отображается и работает правильно, но звук уведомления не воспроизводится. когда приходит уведомление, оно только вибрирует. Обратите внимание, что здесь я могу получать только данные и уведомления. Я пытаюсь настроить звук, но не получается. вот моя полезная нагрузка.

"content_available": true,
    "priority": "high",
    "data": {
        "data": {
            "title": "abc 2020-07-06 11:20:00",
            "is_background": true,
            "message": "2020-07-06 11:20:00",
            "image": "",
            "payload": {
                "article_data": "",
                "message_id": 21
            },
            "timestamp": "2020-07-08T13:20:00.041Z"
        }
    },
    "apns": {
        "headers": {
            "apns-priority": "10"
        },
        "payload": {
            "aps": {
                "sound": "default"
            }
        }
    },
    "aps": {
        "alert": {
            "title": "abc 2020-07-06 11:20:00",
            "subtitle": "2020-07-06 11:20:00",
            "body": "2020-07-06 11:20:00",
            "payload": {
                "article_data": "",
                "message_id": 21
            }
        },
        "sound": "default"
    },
    "notification": {
        "title": "abc 2020-07-06 11:20:00",
        "body": "2020-07-06 11:20:00",
        "content_available": true,
        "click_action": "AboutAssociationActivity",
        "icon": "",
        "payload": {
            "article_data": "",
            "message_id": 21
        },
        "sound": "default"
    }
}

вот мой AppDelegate

    @UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
    
    var window: UIWindow?
    static var badgeCount = 0
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        window = UIWindow(frame: UIScreen.main.bounds)
        UNUserNotificationCenter.current().delegate = self
        
        if (launchOptions?[.remoteNotification] as? [String: AnyObject]) != nil {
            print("Tariqul ")
            
        }
        
        FirebaseApp.configure()
        application.registerForRemoteNotifications()
        Messaging.messaging().`isAutoInitEnabled` = true
        
        registerForPushNotifications()
        guard AppSession.shared.isUserLoggedIn else {
            let coordinator = LoginCoordinator(window: window!)
            coordinator.start(from: window!)
            return true
        }
        
        let coordinator = HomeViewControllerCoordinator()
        coordinator.start(notifyData: nil, from: window!)
        
        
       
        return true
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        print("Tariqul willPresent  \(userInfo)")
        completionHandler([.alert, .sound, .badge])
        
        // completionHandler([.alert])
    }
    
    
    /// Handle tap on the notification banner
    ///
    /// - Parameters:
    ///   - center: Notification Center
    ///   - response: Notification response
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        
        
        let userInfo = response.notification.request.content.userInfo
        
        
        print("Tariqul didReceive  UNUserNotificationCenter \(userInfo)")
        

        let jsonString : [String : Any] = userInfo as! [String : Any]
        
        do {
            
            
            let d  = jsonString["data"] as! String
            let res = try JSONDecoder().decode(NotificationData.self,from:Data(d.utf8))
            
            
            print("Tariqul didReceive  UNUserNotificationCenter 2   \(res.payload.article_data)")
            //            displayNotifcation(message: res.message, title: res.title)
            //            configureNotification()
            
            let coordinator = HomeViewControllerCoordinator()
            // coordinator.notifyData = res
            coordinator.start(notifyData: res, from: window!)
            
            
            let content = UNMutableNotificationContent()
            
            //Default sound
            content.sound = UNNotificationSound.default
            //Play custom sound
            content.sound = UNNotificationSound.init(named:UNNotificationSoundName(rawValue: "pixies.wav"))
            
            
            
        }
        catch {
            print(error)
        }
        
        // print("Tariqul notifyData \(jsonString)")
        UIApplication.shared.applicationIconBadgeNumber =  1
        
        
        print("notifyData    \(extractUserInfo(userInfo: userInfo))")
        
        
        //   print("Tariqul didReceive  \(userInfo)")
        completionHandler()
    }
    
    func extractUserInfo(userInfo: [AnyHashable : Any]) -> String {
        //var info = (title: "", body: "")
        
        
        guard let aps = userInfo["aps"] as? [String: Any] else { return "info" }
        guard let alert = aps["alert"] as? [String: Any] else { return "info" }
        
        let body = alert["body"] as? String ?? ""
        let subtitle = alert["subtitle"] as? String ?? ""
        
        
        
        return "\(subtitle)   \(body) "
    }
    func applicationWillResignActive(_ application: UIApplication) {
        print("WillResignActive")
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        
        
        print("DidEnterBackground")
    }
    
    func applicationWillEnterForeground(_ application: UIApplication) {
        print("WillEnterForeground")
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        
        
        print("DidBecomeActive")
    }
    
    func applicationWillTerminate(_ application: UIApplication) {
        print("WillTerminate")
    }
    
    func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) {
        print("Tariqul  \(remoteMessage.appData)")
    }
}


extension AppDelegate {
    func registerForPushNotifications() {
        
        Messaging.messaging().delegate = self
        //  Messaging.messaging().shouldEstablishDirectChannel = true
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
                [weak self] (granted, error) in
                print("Permission granted: \(granted)")
                
                guard granted else {
                    print("Please enable \"Notifications\" from App Settings.")
                    self?.showPermissionAlert()
                    return
                }
                
                self?.getNotificationSettings()
            }
        } else {
            let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(settings)
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
    @available(iOS 10.0, *)
    func getNotificationSettings() {
        
        UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            print("Tariqul Notification settings: \(settings)")
            guard settings.authorizationStatus == .authorized else { return }
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
    
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken as Data
        let tokenParts = deviceToken.map { data -> String in
            return String(format: "%02.2hhx", data)
        }
        
        let token = tokenParts.joined()
        print("Tariqul Device Token: \(token)")

    }
    
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        
        let dataDict:[String: String] = ["token": fcmToken]
        
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
        
        
        guard !AppSession.shared.isUserLoggedIn else {
            print("Tariqul Firebase registration token: \(fcmToken)")
            let nextPageControl = NotificationTokenSetProtocol()
            nextPageControl.setNotificationToken(FCMToken: fcmToken, completion: { (model, error) in
            })
            return
        }
        
    }
    func displayNotifcation(message:String, title:String){
        debugPrint("displaying notification : \(message)")
        let content = UNMutableNotificationContent()
        content.title = NSString.localizedUserNotificationString(forKey: title, arguments: nil)
        content.body = NSString.localizedUserNotificationString(forKey: message, arguments: nil)
        content.sound = UNNotificationSound.default
        
        let request = UNNotificationRequest(identifier: "requestid", content: content, trigger: nil)
        UNUserNotificationCenter.current().add(request) { (error) in
            if error != nil{
                debugPrint("error in showing notif \(error!.localizedDescription)")
            }
            debugPrint("displaying notification : success")
        }
    }
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("Tariqul didReceive    \(remoteMessage.messageID) \(remoteMessage.appData)")
        do {
            
            
            let d  = remoteMessage.appData["data"] as! String
            //     let aps  = remoteMessage.appData["aps"] as! String
            
            
            let res = try JSONDecoder().decode(NotificationData.self,from:Data(d.utf8))
            
            
            print("Tariqul didReceive   res   \(res.payload.article_data)")
            //            displayNotifcation(message: res.message, title: res.title)
            //            configureNotification()
            //AppDelegate.badgeCount = +1
            UIApplication.shared.applicationIconBadgeNumber = 1
            
            
        }
        catch {
            print(error)
        }
        
        
        
        
    }
    
    
    
    // didReceiveMessage
    //Called if unable to register for APNS.
    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
        
        print("Tariqul error   \(error)")
        
    }
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Tariqul Failed to register: \(error)")
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        
        do {
            //  UIApplication.shared.applicationIconBadgeNumber = 1
            let jsonString : [String : Any] = userInfo as! [String : Any]
            print("Tariqul didReceiveRemoteNotification \(jsonString)")
            
            let d  = userInfo["data"] as! String
            let res = try JSONDecoder().decode(NotificationData.self,from:Data(d.utf8))
            UIApplication.shared.applicationIconBadgeNumber = 1
        }
        catch {
            print(error)
        }
       
    }
    
    func showPermissionAlert() {
        let alert = UIAlertController(title: "WARNING", message: "Please enable access to Notifications in the Settings app.", preferredStyle: .alert)
        
        let settingsAction = UIAlertAction(title: "Settings", style: .default) {[weak self] (alertAction) in
            self?.gotoAppSettings()
        }
        
        let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
        
        alert.addAction(settingsAction)
        alert.addAction(cancelAction)
        
        DispatchQueue.main.async {
            //  self.window?.rootViewController?.present(alert, animated: true, completion: nil)
            
            guard AppSession.shared.isUserLoggedIn else {
                let coordinator = LoginCoordinator(window: self.window!)
                coordinator.start(from: self.window!)
                return
            }
        }
    }
    
    private func gotoAppSettings() {
        
        guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
            return
        }
        
        if UIApplication.shared.canOpenURL(settingsUrl) {
            UIApplication.shared.openURL(settingsUrl)
        }
    }
    
}
...