我是iBeacon和Swift开发的新手,我的应用程序遇到了一些问题。在下面的代码中,我试图检测iBeacon,当我检测到信标的次要值时,我将它附加到我想要播放的链接上。启动程序时出现问题。视频开始播放一秒钟,然后整个应用程序停止并出现以下错误:
由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'应用程序试图以模态方式呈现一个活动控制器.libc ++ abi.dylib:以NSException类型的未捕获异常终止。
var captureSession: AVCaptureSession?
var videoPreviewLayer: AVCaptureVideoPreviewLayer?
var avPlayerViewController = AVPlayerViewController()
var avPlayer:AVPlayer?
let locationManager = CLLocationManager()
let region = CLBeaconRegion(proximityUUID: UUID(uuidString: "8492E75F-4FD6-469D-B132-043FE94921D8")!, identifier: "Estimotes")
let videos = [
19987: NSURL ( string: "http://techslides.com/demos/sample-videos/small.mp4"),
]
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
let knownBeacons = beacons.filter{ $0.proximity != CLProximity.unknown }
if (knownBeacons.count > 0) {
let closestBeacon = knownBeacons[0] as CLBeacon
if let url = self.videos[closestBeacon.minor.intValue] {
self.avPlayer = AVPlayer(url: url as! URL)
self.avPlayerViewController.player = self.avPlayer
}
self.present(self.avPlayerViewController,animated: true) { () -> Void in
self.avPlayerViewController.player?.play()
}
}
}
请问您如何解决该错误?
答案 0 :(得分:1)
问题是每秒都会调用func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion)
范围的回调。因此,呈现视频播放器的代码将每秒执行一次。这可能是第一次工作,但第二次,您将收到错误,因为对self.present(...)
的调用试图呈现您已经呈现的相同视图控制器。 您无法一遍又一遍地呈现相同的视图控制器。
解决方案取决于您希望如何工作。你只想让这个演示发生一次吗?如果是这样,你可以这样做:
if (knownBeacons.count > 0) {
let closestBeacon = knownBeacons[0] as CLBeacon
if let url = self.videos[closestBeacon.minor.intValue] {
// only execute this code once, if avPlayer not created yet
if self.avPlayer == nil {
self.avPlayer = AVPlayer(url: url as! URL)
self.avPlayerViewController.player = self.avPlayer
self.present(self.avPlayerViewController,animated: true) { () -> Void in
self.avPlayerViewController.player?.play()
}
}
}
}