【问题标题】:UIImagePickerController fatal error: unexpectedly found nil while unwrapping an Optional valueUIImagePickerController 致命错误:在展开可选值时意外发现 nil
【发布时间】:2016-01-08 14:36:18
【问题描述】:

我有以下代码:

func startCameraFromViewController(viewController: UIViewController, withDelegate delegate:
protocol<UIImagePickerControllerDelegate, UINavigationControllerDelegate>) -> Bool {

    if (UIImagePickerController.isSourceTypeAvailable(.Camera) == false) {
        return false
    }

    let cameraController = UIImagePickerController()
    cameraController.sourceType = .Camera
    cameraController.mediaTypes = [kUTTypeMovie as String]
    cameraController.allowsEditing = false
    cameraController.delegate = delegate

    presentViewController(cameraController, animated: true, completion: nil)
    return true    
}

它的调用方式如下:

func recordVideoButtonTapped() {
    startCameraFromViewController(self, withDelegate: self)
}

但由于某种原因,我收到以下错误

致命错误:在展开可选值时意外发现 nil

在这一行:

 presentViewController(cameraController, animated: true, completion: nil)

请帮忙调试。

这个问题不同于

What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?

这是一个与解包选项相关的更普遍的问题

这个问题专门针对 UIImagePickerController

【问题讨论】:

标签: ios swift xcode7


【解决方案1】:

我使用的是 Xcode 6.4,它运行良好:

import UIKit
import MobileCoreServices

class FirstViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func startCameraFromViewController(viewController: UIViewController, withDelegate delegate:
        protocol<UIImagePickerControllerDelegate, UINavigationControllerDelegate>) -> Void {

            if (UIImagePickerController.isSourceTypeAvailable(.Camera) == false) {
                println("fail")
                //return false
            }

            let cameraController = UIImagePickerController()
            cameraController.sourceType = .Camera
            cameraController.mediaTypes = [kUTTypeMovie as String]
            cameraController.allowsEditing = false
            cameraController.delegate = delegate

            presentViewController(cameraController, animated: true, completion: nil)
            println("ok")
            //return true
    }

    @IBAction func ToSecondPressed(sender: AnyObject) {
        startCameraFromViewController(self, withDelegate: self)  
    }
}

【讨论】:

  • Xcode 6.4 使用旧的 Swift 语法而不是 Swift 2.0 语法,所以也许你可以试试 Xcode 7.0?
  • 我想是时候升级到Xcode 7了……​​我会试试的。
  • @Das 很好,它适用于 Xcode 7.0.1 和 Swift 2.0。在我的回答中,语法的唯一变化是 print(...) 而不是 println(...) ...
猜你喜欢
  • 2016-01-26
  • 2016-02-29
  • 2020-09-19
  • 2016-09-13
相关资源
最近更新 更多