Forum Xamarin Xamarin.iOS

Strange behaviour, custom notification sound played only in background

nszmmpnszmmp Member ✭✭
edited July 3 in Xamarin.iOS

Hi

I have a strange problem. I want to play notification sounds when app is active, and when in background too, but now, i dont know why the custom sounds played only when app is in background.

Here is my code

 var content = new UNMutableNotificationContent
            {
                Title = title,
                Subtitle = "",
                Body = message
            };

            if (!string.IsNullOrEmpty(soundFileName))
                content.Sound = UNNotificationSound.GetSound(soundFileName);

            var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(0.01, false);

            var request = UNNotificationRequest.FromIdentifier(messageId.ToString(), content, trigger);
            UNUserNotificationCenter.Current.AddNotificationRequest(request, err =>
            {
                if (err != null) throw new Exception($"Failed to schedule notification: {err}");
            });

What can i do to play sounds always?

Best Answer

  • nszmmpnszmmp Member ✭✭
    Accepted Answer

    Hi

    I solved the problem. is somebody need a solution for that:

    • When the application enter foreground mode, than play the custom sound with AVPlayer
    • If the application goes background, disable AVPlayer, and the notification play the sound in the background

    And its work like a charm :smile:

Answers

  • nszmmpnszmmp Member ✭✭
    Accepted Answer

    Hi

    I solved the problem. is somebody need a solution for that:

    • When the application enter foreground mode, than play the custom sound with AVPlayer
    • If the application goes background, disable AVPlayer, and the notification play the sound in the background

    And its work like a charm :smile:

  • ColeXColeX Member, Xamarin Team Xamurai
    edited July 6

    If you want to play sound while app in foreground , you need to implement willPresentNotificationmethod in AppDelegate.cs.

       //objective-c 
        - (void)userNotificationCenter:(UNUserNotificationCenter *)center
                willPresentNotification:(UNNotification *)notification
                withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
           // Update the app interface directly.
    
            // Play a sound.
           completionHandler(UNNotificationPresentationOptionSound);
        }
    

    Search the key word Playing a sound while your app is in the foreground in docs .

Sign In or Register to comment.