你好,我有AVCaptureVideoPreviewLayer
的工作代码..它是条形码阅读器的一部分:
let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
do {
let input = try AVCaptureDeviceInput(device: captureDevice) as AVCaptureDeviceInput
session.addInput(input)
print("input done..")
} catch let error as NSError {
print(error)
}
let output = AVCaptureMetadataOutput()
output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
session.addOutput(output)
output.metadataObjectTypes = output.availableMetadataObjectTypes
previewLayer = AVCaptureVideoPreviewLayer(session: session) as AVCaptureVideoPreviewLayer
previewLayer.frame = self.view.bounds
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.view.layer.addSublayer(previewLayer)
self.view.bringSubviewToFront(self.highlightView)
session.startRunning()
它也在启动和运行,没有任何错误消息,我也在旧的iPhone上使用,我可以看到相机的图片。但是2天前我的iphone被替换了,我没有改变代码中的任何内容。现在应用程序启动但我只能看到黑屏。
有人知道是什么原因引起的吗?
谢谢!
答案 0 :(得分:0)
从iOS 8你需要获得许可,你可以做这样的事情
if ([AVCaptureDevice respondsToSelector:@selector(requestAccessForMediaType: completionHandler:)]) {
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
if (granted) {
// Got the permission
} else {
// Permission has been denied.
}
}];
} else {
// below ios 6
}
你可以在swifth中执行权限方法
if AVCaptureDevice.respondsToSelector(Selector("requestAccessForMediaType"))
{
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (grandted:Bool) -> Void in
//Check if granted and if its true do camera work else permission denied
})
}
else
{
// Below iOS 6
}
答案 1 :(得分:0)
这是我用来测试它的代码:
override func viewDidLoad() {
super.viewDidLoad()
var session = AVCaptureSession.new()
session.sessionPreset = AVCaptureSessionPresetMedium
let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
let input = AVCaptureDeviceInput(device: captureDevice, error: nil) as AVCaptureDeviceInput
session.addInput(input)
print("input done..")
var previewLayer = AVCaptureVideoPreviewLayer(session: session) as AVCaptureVideoPreviewLayer
previewLayer.frame = self.view.bounds
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.view.layer.addSublayer(previewLayer)
session.startRunning()
}
我认为问题在于您没有传递NSError
所要求的AVCaptureDeviceInput
。 Xcode不确定try
语句也试图做什么。我现在只是将nil
传递给构造函数,但是将想要确保你处理它。我还删除了关于设置输出的部分,因为这与我的测试无关。请随意添加。
我在运行iOS 7.1的iPhone 4上进行了测试,以供参考。
答案 2 :(得分:-1)
我将整个代码复制到一个新项目,并在重新部署之后,它要求相机的许可.. :)我不知道这是什么。谢谢你的回答。