未调用UIImagePickerController委托

时间:2018-09-24 02:41:33

标签: ios swift uiimagepickercontroller

使用下面的代码打开相机,但无法调用选取器委托方法。我没有收到任何错误消息。

import Foundation
import UIKit
import MobileCoreServices

class RecVidController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {
        RecVidController.startRecord(delegate: self, sourceType: .camera)
    }

    static func startRecord(delegate: UIViewController & UINavigationControllerDelegate & UIImagePickerControllerDelegate, sourceType: UIImagePickerController.SourceType) {
        guard UIImagePickerController.isSourceTypeAvailable(sourceType) else { return }

        let mediaUI = UIImagePickerController()
        mediaUI.sourceType = sourceType
        mediaUI.mediaTypes = [kUTTypeMovie as String]
        mediaUI.allowsEditing = true
        mediaUI.delegate = delegate
        delegate.present(mediaUI, animated: true, completion: nil)
    }

    @objc func video(_ videoPath: String, didFinishSavingWithError error: Error?, contextInfo info: AnyObject) {
        let title = (error == nil) ? "Success" : "Error"
        let message = (error == nil) ? "Video was saved" : "Video failed to save"

        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.cancel, handler: nil))
        present(alert, animated: true, completion: nil)
    }

}

// MARK: - UIImagePickerControllerDelegate

extension RecVidController: UIImagePickerControllerDelegate {
    private func imagePickerController(_ picker: UIImagePickerController,
                                       didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        dismiss(animated: true, completion: nil)

        guard let mediaType = info[UIImagePickerController.InfoKey.mediaType] as? String,
            mediaType == (kUTTypeMovie as String),
            let url = info[UIImagePickerController.InfoKey.mediaURL] as? URL,
            UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(url.path)
            else { return }

        // Handle a movie capture
        UISaveVideoAtPathToSavedPhotosAlbum(url.path, self, #selector(video(_:didFinishSavingWithError:contextInfo:)), nil)
    }

}

// MARK: - UINavigationControllerDelegate

extension RecVidController: UINavigationControllerDelegate {
}

2 个答案:

答案 0 :(得分:0)

问题是这个声明:

private func imagePickerController(
    _ picker: UIImagePickerController,
    didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

您已声明此方法private,因此Objective-C无法知道它的存在。因此,它无法调用它。

基本上,Cocoa会查看该方法是否已实现,发现它不是(因为您已将其隐藏),然后放弃了。没有明显的损失,因为此委托方法是可选的,并且当未实现该委托方法时,当用户完成选择器后,Cocoa会为您取消选择器。

因此,只需删除private,您应该就可以进行了。这会将委托方法公开给Objective-C,因此将被调用。

(您不必说@objc就可以将它公开给Objective-C,就像您是自己的函数一样,因为您已经声明我们采用了UIImagePickerControllerDelegate,它是一个Objective- C协议。)

答案 1 :(得分:0)

当程序未调用委托方法时,我遇到了类似的问题。

在viewDidLoad()方法中,int k = 0;应该,但是在打开图库的方法中。像这样:

imagePicker.delegate = self
相关问题