How to play a sound when iPhone is on silent?

时间:2019-01-09 21:52:09

标签: ios objective-c react-native avaudioplayer react-native-ios

I am trying to build a react-native alarm application for iOS. I've had a look at a couple of libraries and the one that seemed like the best suit for my project is react-native-alarm, however I am experiencing a problem with it. When my device is on silent mode, the scheduled local notification that is used to wake up the device and play a sound does not do it. I saw people saying that they've tackled this issue by using AVAudioPlayer API that apple provides but I can't seem to make it work. A bit of guidance and help could be beneficial.

I've followed the explanation here : Play sound on iPhone even in silent mode and tried to change the code of the library in order to tackle the silent mode without luck.

Here's my code

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^ (UNNotificationPresentationOptions))completionHandler {

    completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound);

    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"/Library/Ringtones/Constellation" ofType:@"m4r"];
    NSURL *url = [NSURL fileURLWithPath:soundPath];
    audioPlay = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

    [audioPlay play];
}

If there's something Im doing wrong or there is an alternative library that could be used in react-native I'd love to hear that. Im not very experienced when it comes to objective-c so that's why I could have done something stupid in this piece of code.

1 个答案:

答案 0 :(得分:0)

您忘记将会话设置为活动状态:

[[AVAudioSession sharedInstance] setActive:YES error:nil];