網(wǎng)上有很多博客說添加IOS10之后新增的Notification Service Extension才可以推送Apns自定義鈴聲谋竖,實際上是不對的溉贿,簡單的自定義語音推送IOS10之前就已經(jīng)支持柱搜,而且APNS Server與deviceToken直接相關(guān)聯(lián)普泡,自然也不存在許多博客說的殺死App后接受不到推送的問題。
有關(guān)Notification Service Extension多媒體拓展問題可參考http://www.reibang.com/p/56c91be16c3d
本文提供簡單的自定義語音推送解決方案些阅。
修改蘋果原生推送聲音:
(1)App在后臺或者被殺死時狐粱,服務(wù)器給你推送的userinfo中sound字段的value和你本地的聲音文件名一致時舀寓,這樣就可以播放你本地自定義的語音文件(mp3,wav等常見語音格式都可以支持)。
(2)App運行在前臺時大部分App會關(guān)閉掉UNNotificationPresentationOptionSound權(quán)限肌蜻,當你有類似美團接單互墓,支付寶到賬等需前臺響鈴的需求時需要自己寫響鈴方法,這里主要有兩種解決方案蒋搜。
方案1播放系統(tǒng)音效
/// 播放通知鈴聲
- (void)jyeb_playSoundWithFilename:(NSString *)filename fileExtension:(NSString *)fileExtension {
// 系統(tǒng)值 kSystemSoundID_Vibrate = 0x00000FFF
SystemSoundID sound = 1;
// 轉(zhuǎn)換 URL
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:filename ofType:fileExtension];
NSURL *soundURL = [NSURL fileURLWithPath:soundFilePath];
// 生成系統(tǒng)音效id
AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &sound);
// 播放系統(tǒng)音效
AudioServicesPlaySystemSound(sound);
}
將此方法在應(yīng)用在前臺處理推送的方法中調(diào)用篡撵,注意區(qū)分iOS10前后處理方法的不同。
方案2:AVAudioPlayer播放
單例一個AVAudioPlayer控制類
/// 播放音頻
- (void)playWithContentsOfFileName:(NSString *)fileName fileType:(NSString *)fileType callBack:(EBAPNsAudioCompleted)callBack
{
self.callBack = callBack;
[self activePlayback];
// 調(diào)節(jié)音量
[self setHighVolume];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:fileName ofType:fileType];
NSURL *soundURL = [NSURL fileURLWithPath:soundFilePath];
self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:soundURL error:nil];
self.audioPlayer.delegate = self;
// 開始播放
[self.audioPlayer prepareToPlay] ;
[self.audioPlayer play];
}
// 播放器激活
- (void)activePlayback
{
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:NULL];
[[AVAudioSession sharedInstance] setActive:YES error:NULL];
}
// 播放器休眠
- (void)disactivePlayback
{
[[AVAudioSession sharedInstance] setActive:NO error:NULL];
}
// 播放完成
- (void) playCompleted
{
if (self.callBack) {
self.callBack() ;
}
}
#pragma mark - AVAudioPlayerDelegate
// 播放結(jié)束回調(diào)
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
// 設(shè)置回初始音量
[self setNormalVolume] ;
[self disactivePlayback] ;
[self performSelectorOnMainThread:@selector(playCompleted) withObject:nil waitUntilDone:NO] ;
}
這里我們推薦使用第一種方法豆挽,通過系統(tǒng)方法進行播放育谬。