语言:Swift 4.2。
问题是iOS 13.0对我自iOS 12.0起使用的相同代码的要求。与许多人在更新Xcode之后相同的问题。 先前安装的macOS Catalina和Xcode 11.2。
结果:“ imageBuffer”仅在iOS 13.0或更高版本中可用。
代码(课程前带有“ @available”)
import UIKit
import AVKit
import Vision
@available(iOS 13.0, *)
class VideoViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate
{
let identifierLabel: UILabel = {
let label = UILabel()
label.backgroundColor = .white
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override func viewDidLoad()
{
super.viewDidLoad()
let captureSession = AVCaptureSession()
captureSession.sessionPreset = .photo
guard let captureDevice = AVCaptureDevice.default(for: .video) else { return }
guard let input = try? AVCaptureDeviceInput(device: captureDevice) else { return }
captureSession.addInput(input)
captureSession.startRunning()
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
view.layer.addSublayer(previewLayer)
previewLayer.frame = view.frame
let dataOutput = AVCaptureVideoDataOutput()
dataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue"))
captureSession.addOutput(dataOutput)
setupIdentifierConfidenceLabel()
}
fileprivate func setupIdentifierConfidenceLabel() {
view.addSubview(identifierLabel)
identifierLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -32).isActive = true
identifierLabel.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
identifierLabel.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
identifierLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
//connection.videoOrientation = AVCaptureVideoOrientation.landscapeLeft
let pixelBuffer: CVPixelBuffer = sampleBuffer.imageBuffer!
let ciimage : CIImage = CIImage(cvPixelBuffer: pixelBuffer)
let _ : UIImage = self.convert(cmage: ciimage)
guard let model = try? VNCoreMLModel(for: FaceClassifier2().model) else { return }
let request = VNCoreMLRequest(model: model)
{ (finishedReq, err) in
guard let results = finishedReq.results as? [VNClassificationObservation] else { return }
guard let firstObservation = results.first else { return }
print(firstObservation.identifier, firstObservation.confidence)
DispatchQueue.main.async {
self.identifierLabel.text = "\(firstObservation.identifier) \(firstObservation.confidence * 100)"
}
}
try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request])
}
// Convert CIImage to CGImage
func convert(cmage:CIImage) -> UIImage {
let context:CIContext = CIContext.init(options: nil)
let cgImage:CGImage = context.createCGImage(cmage, from: cmage.extent)!
let image:UIImage = UIImage.init(cgImage: cgImage)
return image
}
}
问题:是否可以在没有@available的情况下使其在iOS 12.0上运行? 原因是大多数人仍然根本无法购买新iPhone和安装iOS 13.0。
P.S:Apple更新不再让我们的生活变得更轻松。