0

I have been breaking my head for almost a week, to create my own sound when I generate push notifications in iOS. Version is 13.4. Problem is all push notifications are silent, even though all settings in iPhone is correct. Below is my AppDelegate.swift file. I don't know where and how to make a change so that I can generate my own sound when I receive push notifications. Please can you let me know where is the mistake? Also, I am new to iOS. So any help regarding this would be highly appreciated.

import UIKit
import Firebase
import UserNotifications
import FirebaseMessaging
import FirebaseInstanceID


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = (self as UNUserNotificationCenterDelegate)

            UNUserNotificationCenter.current().requestAuthorization(
                options: [.alert, .badge, .sound],
                completionHandler: {_, _ in })
            Messaging.messaging().delegate = (self as MessagingDelegate)
        } else {
            let settings: UIUserNotificationSettings =

                UIUserNotificationSettings(types: [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(settings)
        }
        UIApplication.shared.registerForRemoteNotifications()
        UIApplication.shared.applicationIconBadgeNumber = 0
        FirebaseApp.configure()
        NSSetUncaughtExceptionHandler { exception in
            print(exception)
            print(exception.callStackSymbols)
        }

        return true
    }

    // The callback to handle data message received via FCM for devices running iOS 10 or above.

    func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) {
        print("Remote message is ", remoteMessage.appData)
    }

    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, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("i am not available in simulator \(error)")
    }

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        let token = Messaging.messaging().fcmToken
        regToken=token!
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {

        print("didReceiveRemoteNotification", userInfo)
            let content = UNMutableNotificationContent()
            if let title = userInfo["title"]
            {
                content.title = title as! String
            }
            if let title = userInfo["text"]
            {
                content.body = title as! String
            }
            content.userInfo = userInfo
            //content.sound = UNNotificationSound.default
            content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "tornado_alarm.caf"))

            let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 0.5, repeats: false)
            let request = UNNotificationRequest(identifier:"rig", content: content, trigger: trigger)

            UNUserNotificationCenter.current().delegate = (self as UNUserNotificationCenterDelegate)
            UNUserNotificationCenter.current().add(request) { (error) in
                if let getError = error {
                    print("didReceiveRemoteNotification error is ", getError.localizedDescription)
                }
            }
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        print("willPresent", notification.request.content.userInfo)

        if notification.request.identifier == "rig"{
            completionHandler( [.alert,.sound,.badge])
        }else{
            completionHandler([.alert, .badge, .sound])
        }

    }

    func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        //Handle the notification
        completionHandler(
            [UNNotificationPresentationOptions.alert,
             UNNotificationPresentationOptions.sound,
             UNNotificationPresentationOptions.badge])
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        Messaging.messaging().apnsToken = deviceToken
        let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
        print("Device Token Is ", deviceTokenString)

    }


    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    }
}
TylerP
  • 9,600
  • 4
  • 39
  • 43
DBHari
  • 63
  • 6
  • Can you share your entire payload? That would help us see how you're sending the sound to yourself – mfaani Apr 13 '20 at 01:24
  • Thanks for your help. I dont know how to get the payload. Please can you tell me how to do? I can generate and put it immediately – DBHari Apr 13 '20 at 09:08
  • I'm not familiar with firebase. But I'm guessing whereever you're adding your fields, it has a section that shows you the final payload. Also what does the print log for `remoteMessage.appData` look like? I want to see where in your payload the sound name is coming through. Also have you added the sound file to your app's bundle? – mfaani Apr 13 '20 at 14:01
  • Thanks for your help. Yes I have added the sound file in my bundle. I have developed android and iOS version of this app and they both communicate using firebase . I have just sent a push notification from android to iOS and the following was logged in output window [AnyHashable("gcm.message_id"): 1586789225196976, AnyHashable("google.c.a.e"): 1, AnyHashable("aps"): { alert = { body = "Message Sent From A To B."; title = "Tracker App"; }; }, AnyHashable("google.c.sender.id"): 647864626463] I have added the audio file name in Appdelegate. Is that not enough? – DBHari Apr 13 '20 at 14:52
  • kindly edit the question and include that payload in your question. Also see [here](https://stackoverflow.com/a/39346405/5175709) to find a suitable payload structure. The name of the sound file should come from the server. – mfaani Apr 13 '20 at 17:50
  • I am extremely sorry for the delay. I was not able to upload the app to test because of this covid issue. I am going to upload this tonight and check. For now, I will mark this as resolved. Apologies for the delay. – DBHari Apr 26 '20 at 19:57

0 Answers0