2017-01-20 24 views
-1

我正在使用AVCaptureDeviceInput类,它是Swift中AVFoundation的一部分。 iniitializer抛出一个异常,我想找出异常的原因。应该有一个NSError对象给出信息。雨燕调用API参考文档是:从Swift 3调用基础类的Objective-C替代实现

Declaration 
init(device: AVCaptureDevice!) throws 
Parameters 
device 
The device from which to capture input. 
outError 
If an error occurs during initialization, upon return contains an NSError object describing the problem. 

Xcode不是让我第二个参数给我的电话加入到AVCaptureDeviceInput(device: device!)。在我看来,有关outError参数的文档是错误的。

API参考也有一个Objective-C的定义如下:

Declaration 
- (instancetype)initWithDevice:(AVCaptureDevice *)device 
        error:(NSError **)outError; 
Parameters 
device 
The device from which to capture input. 
outError 
If an error occurs during initialization, upon return contains an NSError object  describing the problem. 
Return Value 
An input initialized to use device. 

我见过的示例代码在线返回的NSError,但它在斯威夫特2.有没有一种方法我可以得到在Swift 3中?

回答

2

It appears to me that the documentation is wrong about having an outError parameter

那么,这是没有错的。请参阅throws标记?这就是你在Swift中获取错误参数的方法。您必须使用try来调用此初始化程序。如果您嵌入此在do,你在catch错误:但

do { 
    let d = try AVCaptureDeviceInput(device:aDevice) 
} catch { 
    print(error) 
} 

,请注意,这不会帮助你,除非框架真的没有良好的秩序和传递一个NSError给你。如果你是崩溃(例如,因为你想解开nil或类似的东西),你仍然会崩溃。

+0

请参阅我的在线书籍:http://www.apeth.com/swiftBook/ch05.html#_throwing_and_catching_errors讨论如何对应Objective-C错误:(NSError **)outError'结构该部分的结尾。 – matt