我已经查看了 Stackoverflow,但无法得到答案。我想创建停止在另一个 ViewController 中播放声音的功能。但是当我点击停止按钮时,它崩溃了并显示“EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)”。这是我的代码。
第一个 View Controller
import UIKit
import AVFoundation
class FirstVC: UIViewController {
var metronome: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
do {
let resourcePath1 = Bundle.main.path(forResource: "music", ofType: "mp3")
let url = NSURL(fileURLWithPath: resourcePath1!)
try metronome = AVAudioPlayer(contentsOf: url as URL)
metronome.prepareToPlay()
metronome.play()
} catch let err as NSError {
print(err.debugDescription)
}
}
另一个Viewcontroller是
import UIKit
class SecondVC: UIViewController {
var metronomePlay = FirstVC()
@IBAction func stopBtnPressed(_ sender: Any) {
metronomePlay.metronome.stop() //"EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)"
}
}
最佳答案
从今天的 swift 4.1 开始,这段代码对我有用:
将其放入发送 Controller 中:
NotificationCenter.default.post(name: Notification.Name(rawValue: "disconnectPaxiSockets"), object: nil)
将其放入接收 Controller viewDidLoad() 或 viewWillAppear() 中:
NotificationCenter.default.addObserver(self, selector: #selector(disconnectPaxiSocket(_:)), name: Notification.Name(rawValue: "disconnectPaxiSockets"), object: nil)
然后是接收 Controller 类中的以下函数:
@objc func disconnectPaxiSocket(_ notification: Notification) {
ridesTimer.invalidate()
shared.disconnectSockets(socket: self.socket)
}
关于ios - 快速从另一个 ViewController 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42135402/