简体   繁体   English

将照片从照片库导入Xcode中的应用程序

[英]Importing image from photo library into an app in xcode

My app keeps crashing and I don't know why. 我的应用不断崩溃,我不知道为什么。 I'm working on a tabbed application part by part and testing it every time I get a part of it done. 我正在逐部分地研究选项卡式应用程序,并在每次完成一部分时对其进行测试。 Right now I'm working on trying to import an image from the user's device but I can't seem to get it. 目前,我正在尝试从用户的设备导入图像,但似乎无法获取。

I'm currently using Xcode 10.2.1 and I understand that there has been some changes to the delegate methods and I have changed them. 我当前正在使用Xcode 10.2.1,并且我知道委托方法已经进行了一些更改,并且已经对其进行了更改。 It succeeds in building but whenever I tap that one particular tab where I would like to import an image, it crashes. 它可以成功构建,但是每当我点击要导入图像的那个特定选项卡时,它就会崩溃。

class UserImage: UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    var imagePickerController : UIImagePickerController!

    @IBOutlet var ImageView: UIImageView!

    @IBAction func Edit(_ sender: Any) {
        imagePickerController.delegate = self
        imagePickerController.sourceType = .photoLibrary

        present(imagePickerController, animated: true, completion: nil)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
    {
        if let image = info[.originalImage] as? UIImage { 
            ImageView.image = image
        } else {
            print("Take another")
        }

        self.dismiss(animated: true, completion: nil)
    }

It is crashing because you never actually initialized the UIImagePickerController . 它崩溃是因为您从未真正初始化过UIImagePickerController Since you marked the imagePickerController as a non optional value, your app is going to crash when you try to reference it but it is still nil . 由于您将imagePickerController标记为非可选值,因此当您尝试引用它时,您的应用将崩溃,但它仍然为nil Add this line to the beginning of your Edit function to initialize the variable: 将此行添加到Edit函数的开头以初始化变量:

imagePickerController = UIImagePickerController()

Edit: Alternatively, as @rmaddy mentioned, you could just make the controller a local variable of the function. 编辑:或者,如@rmaddy所述,您可以使控制器成为函数的局部变量。 In your example, there is no need to make it a property of the class. 在您的示例中,无需使其成为类的属性。 Essentially you would just remove the declaration from the top of your class and instead declare it inside the function: 本质上,您只需要从类的顶部删除声明,而是在函数内部进行声明:

let imagePickerController = UIImagePickerController()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM