0x00 进退两难
在利用AVPlayer
播放网络 mp3 时,因为有监听状态,所以移除监听是必须的
不然会出现以下错误:
An instance 0x174016100 of class AVPlayerItem was deallocated while key value observers were still registered with it.
不移除观察者时,导致的崩溃:
Trapped uncaught exception 'NSInternalInconsistencyException', reason: 'An instance 0x174016100 of class AVPlayerItem was deallocated while key value observers were still registered with it. Current observation info: <NSKeyValueObservationInfo 0x1708215a0> (
<NSKeyValueObservance 0x17484d530: Observer: 0x15c14ca00, Key path: status, Options: <New: YES, Old: YES, Prior: NO> Context: 0x0, Property: 0x174848d00>
<NSKeyValueObservance 0x17484e9a0: Observer: 0x15c14ca00, Key path: playbackLikelyToKeepUp, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x174841f20>
<NSKeyValueObservance 0x174454610: Observer: 0x15c14ca00, Key path: playbackBufferEmpty, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x174849ff0>
)'
然而,有个蛋疼的操作出现了
当移除观察者时
另外一个Bug出现了
Trapped uncaught exception 'NSInvalidArgumentException', reason: 'An instance of AVPlayer cannot remove a time observer that was added by a different instance of AVPlayer.'
这移除不行!
这不移除也不行!
这要怎么玩??
0x01 情况分析
1.播放音频
1.1移除前一个音频的监听状态(如果存在)
1.2添加新的监听状态
2.状态监听回调方法
2.1成功则播放
2.2失败
2.2.1第1次失败,尝试再次播放 -> 走步骤1
2.2.2第2次失败,移除监听状态
就是在步骤 2.2.2
,出现了进退两难的情况
0x02 解决方案
既然移除是必须的
那就只能走移除!
但是移除又会导致:
Trapped uncaught exception 'NSInvalidArgumentException', reason: 'An instance of AVPlayer cannot remove a time observer that was added by a different instance of AVPlayer.'
只能前进
如何后退呢?
如果你能想到的话
你已经知道我要说什么了
如果你还没想到
继续往下看
iOS中有个捕获异常,防止崩溃的机制:@try @catch
@try {
// 可能存在异常
[self.player removeTimeObserver:self.timeObserver];
} @catch (NSException *exception) {
// 查看异常
NSLog(@"RemoveObserver:%@",exception);
} @finally {
// 去掉 finally 也可以
}
虽然这个捕获异常的机制
捕获的异常有限
但这里确实能防止
应用崩溃
Nice!
iOS 验证码输入框
https://github.com/xjh093/JHVerificationCodeView