【发布时间】:2017-03-25 06:53:13
【问题描述】:
我正在创建一个音频应用程序,我希望在屏幕关闭时继续播放音频。(它在屏幕打开时在后台运行良好。)
在 xcode 上启用了后台模式(我在 Info.plist 中设置了“audio”值。)并且我实现了“AVAudioSession.sharedInstance”,但是当我的设备中的屏幕关闭时应用程序崩溃。有解决这个问题的想法吗?
这是完整的代码
var player:AVAudioPlayer!
init(withStartingClosure block1:@escaping(_ dict:[String:Any],_ index:Int) -> Void,andStopingClosure block2:@escaping(_ index:Int) -> Void,finishedAllClosure block3:((_ finished:Bool) -> Void)? = nil) {
self.didStartPlaying = block1
self.didStopPlaying = block2
self.didFinishPlaying = block3
}
deinit {
self.mode = .stopped
}
}
extension AudioPlayer {
func getURL(ofAudio name:String) -> URL {
let url = URL(string: name)!
let nm = url.deletingPathExtension().absoluteString
let type = url.pathExtension
let path = Bundle.main.url(forResource: nm, withExtension: type)!
return path
}
func setupPlayer(withData data:[String:Any]){
let name = data["audio"] as! String
var idx = self.currentIndex - 1
if idx < -1 {
idx = -1
}
print("\nCurrentIndex = \(idx),and Audio is = \(data)")
let path = self.getURL(ofAudio: name)
do {
try self.setupAudioSession()
self.player = try AVAudioPlayer(contentsOf: path)
self.player.delegate = self
if self.player.prepareToPlay() == true {
self.player.play()
self.didStartPlaying?(data, idx)
}else{
print("----------Can't Play \(data)")
}
}
catch {
print(error.localizedDescription)
let alert = UIAlertView(title: "Error!", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayback)
} catch {
fatalError("error1")
}
do {
try session.setActive(true)
} catch {
fatalError("sessionError")
}
}
我收到的错误。 由于未捕获的异常“NSRangeException”而终止应用程序,原因:“-[UITableView _contentOffsetForScrollingToRowAtIndexPath:atScrollPosition:]
func reloadCell(AtIndexPath indexPath:IndexPath,shouldStop value:Int = 0){
//"value" is default value.
// if it is 1. it means stop playing animation of this TableViewCell
let cell = self.table.cellForRow(at: indexPath)
self.configureCell(cell, atIndexPath: indexPath, shouldStop: value)
//This is the code which get crash
self.table.scrollToRow(at: indexPath, at: .bottom, animated: true)
}
【问题讨论】:
-
崩溃在哪一行?你能把源代码精简到最少吗?
-
是的,我把代码最小化了。
-
鉴于崩溃,它与您发布的代码无关。它与您的 UI 和 UITableView 有关。在 Xcode 中,转到 Breakpoints Navigator (Command-7) 并使用左下角的 + 设置异常断点。然后 Xcode 将在问题发生而不是稍后发生时中断。
-
感谢您的建议,我在另一个 viewController 中收到错误消息。你知道它为什么会崩溃吗?
-
当它崩溃时,您需要查看传递给
reloadCell的 indexPath 并尝试找出它无效的原因。