[iOS] UIImagePickerController Use Photo / Cancel button event

服用下列的程式碼,可以取得拍照完的照片,還有使用者按下 cancel 事件。重點的部份加入紅字來區別。


class ViewController: UIViewController {
    fileprivate var photoPickerController = UIImagePickerController()
    let notificationIdentifier: String = "StartCamera"

    override func viewDidLoad() {
        // Register to receive notification
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.cameraSetUp), name: NSNotification.Name(rawValue: notificationIdentifier), object: nil)
    }

    func cameraSetUp(){
        photoPickerController.sourceType = .camera
        photoPickerController.cameraDevice = .front
        photoPickerController.delegate = self
        present(photoPickerController, animated: true)

    }
    @IBAction func showCamera(_ sender: Any) {
        cameraSetUp()
    }
}

extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        guard let storyboard = storyboard else {return}
        let viewController = storyboard.instantiateViewController(withIdentifier: "EditingViewController")
        picker.dismiss(animated: true)
        present(viewController, animated: true)
    }

    public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
    }
}

2) EditingViewController class code

class EditingViewController: UIViewController {
    let notificationIdentifier: String = "StartCamera"

    @IBAction func dismissButtonTapped(_ sender: Any) {
        // Post a notification
        dismiss(animated: true)
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: notificationIdentifier), object: nil)
    }
}

相關文章

寫留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *