How to add sound for UILocalNotification?

2019-04-05 03:34发布

问题:

I have done with basic notification for my App. I want to add sound effect to my notification.

UILocalNotification *localNotification = [[UILocalNotification alloc] init];
if (localNotification == nil)
    return;

localNotification.fireDate = [NSDate date];
//localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.alertBody = msg;
localNotification.soundName = @"Morse.aiff";

[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];

How to add sound effect?

回答1:

You may want to start with reading Preparing Custom Alert Sounds of the Local and Push Notification Programming Guide (make sure that your custom sound is shorter than 30s).

If you want to use the default sound: use UILocalNotificationDefaultSoundName (as suggested by Euroboy)

Update: You seem to be not the only person experiencing this problem. A possible (but of course not a good) solution is described here.



回答2:

In my case the problem was that I forgot to register for UIUserNotificationTypeSound. Without registration to UIUserNotificationTypeSound your App will not have the 'Sounds' option available under the Notifications Settings.

Here is the code snippet from the Local and Remote Notification Programming Guide (tilo already added a link to it above).

UIUserNotificationType types = UIUserNotificationTypeBadge |
UIUserNotificationTypeSound | UIUserNotificationTypeAlert;

UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];

[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];

After adding that code you can enable the sound option in Notification Settings for your App.



回答3:

I had similar problem while trying to play mp3 file as local notification sound. Sound was shorter than 30 seconds, it was bundled, everything appears regular on the surface. After few hours i have realised that problem was caused by online mp3 cutter tool. I have find better editor, and file became playable on notification.

If mp3 file is edited with some tool, it is possible that something was missed by edit tool.

May be your problem is also caused by sound editor, or sound format converter.



回答4:

I found really simple solution for playing custom sound in local notification. 1. Normally sound will be work perfectly with aiff format. 2. When you added custom sound, please check if this sound added to the "Build Phases" 3. You already added your custom sound but basic system alert playing again? - delete application from your device and reboot. After connect your device and compile application again. 4. Profit! it will be work!

PS: This is solution if you have iOS 10. How i am understanding this is system bag..



回答5:

You need to make sure the resource file has your Target membership selected. For my case, it was not checked, and notification was still the system default one.