我目前正在尝试构建一个有趣的相机应用程序并遇到问题。
我正在使用Apple为您提供照片或视频拍摄过程的示例。在这里找到:
https://developer.apple.com/library/content/samplecode/AVCam/Introduction/Intro.html
我在使用PhotoCaptureDelegate
时遇到问题。因此,当用户拍照时,它会将其保存到用户照片库。我想要做的是,它捕获照片后,我想存储照片的photoData
对象。这样我就可以在保存之前将照片作为预览显示在另一个视图上。
这是Apple建议使用的:
func capture(_ captureOutput: AVCapturePhotoOutput, didFinishCaptureForResolvedSettings resolvedSettings: AVCaptureResolvedPhotoSettings, error: Error?) {
if let error = error {
print("Error capturing photo: \(error)")
didFinish()
return
}
guard let photoData = photoData else {
print("No photo data resource")
didFinish()
return
}
PHPhotoLibrary.requestAuthorization { [unowned self] status in
if status == .authorized {
PHPhotoLibrary.shared().performChanges({ [unowned self] in
let creationRequest = PHAssetCreationRequest.forAsset()
creationRequest.addResource(with: .photo, data: photoData, options: nil)
if let livePhotoCompanionMovieURL = self.livePhotoCompanionMovieURL {
let livePhotoCompanionMovieFileResourceOptions = PHAssetResourceCreationOptions()
livePhotoCompanionMovieFileResourceOptions.shouldMoveFile = true
creationRequest.addResource(with: .pairedVideo, fileURL: livePhotoCompanionMovieURL, options: livePhotoCompanionMovieFileResourceOptions)
}
}, completionHandler: { [unowned self] success, error in
if let error = error {
print("Error occurered while saving photo to photo library: \(error)")
}
self.didFinish()
}
)
}
else {
self.didFinish()
}
}
}
如何从我的委托中取出photoData
对象并将其传递回我的视图控制器,即调用此委托?
答案 0 :(得分:1)
有几种方法可以解决这个问题。您也可以让您的视图控制器拥有照片捕获代理(如Apple的示例)并在拍摄照片后将其传回。你也可以让你的视图控制器成为照片捕获委托,而不用担心传递任何东西!
1)将照片重新传回
有(再次)有几种方法可以做到这一点。您可以让委托将值传递回控制器。您也可以让代表告诉控制器它已完成,并让控制器来抓取照片。我将在下面解释第二种方式。
看看Apple的例子,我们可以看到PhotoCaptureDelegate
已经告诉控制器何时完成!每当创建PhotoCaptureDelegate
对象时,都会传递completed
块。
要允许控制器抓取照片,我们只需要公开照片对象!
private var photoData: Data? = nil
中的PhotoCaptureDelegate
更改为public var photoData: Data? = nil
CameraViewController
块时completed
,您现在拥有了照片数据: ...
, completed: { [unowned self] photoCaptureDelegate in
self.sessionQueue.async { [unowned self] in
self.inProgressPhotoCaptureDelegates[photoCaptureDelegate.requestedPhotoSettings.uniqueID] = nil
if let photoData = photoCaptureDelegate.photoData {
// You now have the photo data!
// You can pass this to another method in the Controller now
}
}
}
...
2)将控制器视为AVCapturePhotoCaptureDelegate
解决此问题的另一种方法是让ViewController
成为AVCapturePhotoCaptureDelegate
。那么你已经在视图控制器中拥有了照片数据!它可能看起来像这样:
class MyViewController: UIViewController, AVCapturePhotoCaptureDelegate {
...
func capture(_ captureOutput: AVCapturePhotoOutput, didFinishCaptureForResolvedSettings resolvedSettings: AVCaptureResolvedPhotoSettings, error: Error?) {
guard let photoData = photoData else {
return
}
// You now have your photo data!
}
}