imagePickerController:didFinishPickingMediaWithInfo与protocol' UIImagePickerControllerDelegate'

时间:2015-07-19 17:11:49

标签: ios swift ios8 uiimagepickercontroller xcode7

以下是完整错误:

  

Objective-C方法' imagePickerController:didFinishPickingMediaWithInfo:'方法提供       ' imagePickerController(_:didFinishPickingMediaWithInfo:)'       与可选的需求方法冲突' imagePickerController(_:didFinishPickingMediaWithInfo :)'        在协议' UIImagePickerControllerDelegate'

它发生在我的ViewController.swift文件中的第一个函数上:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        ImageView.contentMode = .ScaleAspectFit
        ImageView.image = pickedImage
    }

    dismissViewControllerAnimated(true, completion: nil)
}

我正在尝试按照本教程:http://www.codingexplorer.com/choosing-images-with-uiimagepickercontroller-in-swift/

从错误方法

我收集到有一个方法didFinishPickingMediaWithInfo它是从imagePickerController基类得到的,它并不像我试图覆盖它。但这就是我所知道的。我在网上找到的所有imagePickerController函数都是这样的。我做错了什么?

我正在使用Xcode 7,如果这有所不同。 ]

Screenshot 1

4 个答案:

答案 0 :(得分:22)

正确的功能头是:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    <#code#>
}

请注意信息词典声明中的String而不是NSObject

我不确定为什么文档说你必须写NSObject,但String是正确的。

如果您实施任何协议方法,我建议您使用Xcode的自动完成功能,以确保不会遇到这样的问题。

enter image description here

我不确定Xcode从哪里获得自动完成但它似乎始终与实际的编译器同步,这最终是你必须担心的一件事而不是一些在线苹果文档!特别是在框架不断变化甚至语言本身正在发展的时代。

答案 1 :(得分:4)

如果您使用的是Xcode 7,那么您可能会定位到iOS 9,然后方法签名略有改变:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {

为:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

NSObject已更改为String

Swift 3 中,它变为

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])

答案 2 :(得分:0)

以下是UIImagePickerController的 didFinishPickingMediaWithInfo 委托的格式:

 public func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])

在您的情况下,在函数参数中使用 String 而不是 NSObject

Screenshot 1

答案 3 :(得分:0)

我有这个问题在XCode 8中编写UIImagePickerControllerDelegate的扩展

XCode 8自动完成功能为第一个参数生成一个带下划线的方法签名。这会在Swift编译器中创建分段错误。删除下划线可以解决问题。

// CRASH SegFault 11
@objc protocol MyDelegate: UIImagePickerControllerDelegate {

}
extension MyDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        // code
    }
}


// DOESN'T CRASH 
@objc protocol MyDelegate: UIImagePickerControllerDelegate {

}

extension MyDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        // code
    }
}