UNNotification: Custom Sound for LocalNotification

2019-03-06 03:00发布

问题:

I am firing the Local Notification. Since UILocalNotification class is deprecated in iOS10 I have used UserNotifications.framework

When i try to set the custom sound for notification, the default sound is playing all time.

here is my code:

- (IBAction)fireLocalNotification:(id)sender {

    UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
    content.title = [NSString localizedUserNotificationStringForKey:@"Hello!" arguments:nil];
    content.body = [NSString localizedUserNotificationStringForKey:@"Hello_message_body"
                                                         arguments:nil];
    content.sound = [UNNotificationSound soundNamed:@"sound.mp3"];

    // Deliver the notification in five seconds.
    UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger
                                                  triggerWithTimeInterval:5 repeats:NO];

    UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
                                                                          content:content trigger:trigger];

    // Schedule the notification.
    UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
    [center addNotificationRequest:request withCompletionHandler:^(NSError *error){

        if(!error){

            NSLog(@"Completion handler for notification");
        }

    }];
}

my sound fine- sound.mp3 is present in project bundle itself.

more info: https://developer.apple.com/reference/usernotifications/unusernotificationcenter?language=objc

回答1:

Try deleting app from device, Clean and Run again app in device.

Some Times resource are not get proper updated, I think, That is the problem in your case.



回答2:

Long audio-files are not supported

Is your file longer then 30 seconds? If yes, it will not work. Only files shorter then 30 seconds are available. If the file is longer then 30 seconds then it will be replaced with default sound.

UNNotificationSound documentation