如何使用Swift允许用户选择图片?

111

我正在使用Swift编写我的第一个iOS应用程序(仅限iPhone)。主应用程序视图应允许用户从照片库中选择图像。

我找到了以下的ViewController.swift示例代码:

class ViewController: UIImagePickerController, UINavigationControllerDelegate, UIImagePickerControllerDelegate  {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {

        var imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self
        imagePickerController.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum
        imagePickerController.allowsEditing = true
        self.presentViewController(imagePickerController, animated: true, completion: { imageP in

        })
    }


    func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) {
        let selectedImage : UIImage = image
        println(selectedImage)
    }

}

并且拥有以下的视图控制器场景 -

View Controller
 - Top Layout Guide
 - Bottom Layout Guide
 - View
   - Image View
First Responder
Exit

但是当我启动应用程序时,只显示黑屏。我做错了什么?我找到的另一个示例代码是用Objective-C编写的,这对我没有帮助。


一个问题可能是didSelectRowAtIndePath是UITableViewDelegate的委托调用。根据您的场景布局和代码,这里没有使用tableview,并且您的ViewController不是UITableViewDelegate。也许从一个能够工作的空白项目开始,添加一个按钮并从按钮按下触发您的代码。 - Michael Wildermuth
@LA_ 我不明白为什么这里涉及到了tableView函数? - Dekel Maman
它已经可用且经过充分测试,请前往以下链接查看: https://dev59.com/W1gR5IYBdhLWcg3wHqTB#49169339 - Mr.Javed Multani
请查看以下与编程有关的内容:https://theswiftdev.com/picking-images-with-uiimagepickercontroller-in-swift-5/ - Rinto Andrews
20个回答

148

如果你只是想让用户使用UIImagePickerController选择图片,请使用以下代码:

import UIKit


class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    @IBOutlet var imageView: UIImageView!
    @IBOutlet var chooseBuuton: UIButton!
    var imagePicker = UIImagePickerController()

    @IBAction func btnClicked() {

        if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
            print("Button capture")

            imagePicker.delegate = self
            imagePicker.sourceType = .savedPhotosAlbum
            imagePicker.allowsEditing = false

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

    func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
        self.dismiss(animated: true, completion: { () -> Void in

        })

        imageView.image = image
    }
}

如果我不想让用户按按钮选择图片怎么办? - LA_
从函数中删除@IBAction,并在需要时调用该函数,例如在viewDidLoad或任何时间都可以随时调用它。 - Dekel Maman
谢谢。它说“尝试在未在窗口层次结构中的<MyApp.ViewController: 0x7fdb838360a0>上呈现<UIImagePickerController: 0x7fdb84029800>”。我应该在场景中添加一些东西吗? - LA_
3
我点赞了,因为这真的很有帮助。只需将NSDictionary更改为[NSObject: AnyObject],就可以正常工作了! - scubasteve623
https://theswiftdev.com/picking-images-with-uiimagepickercontroller-in-swift-5/ - Rinto Andrews
显示剩余3条评论

122
完整的可拷贝粘贴的图像选择器,基于@user3182143的答案,适用于Swift 4
import Foundation
import UIKit


class ImagePickerManager: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    var picker = UIImagePickerController();
    var alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
    var viewController: UIViewController?
    var pickImageCallback : ((UIImage) -> ())?;
    
    override init(){
        super.init()
        let cameraAction = UIAlertAction(title: "Camera", style: .default){
            UIAlertAction in
            self.openCamera()
        }
        let galleryAction = UIAlertAction(title: "Gallery", style: .default){
            UIAlertAction in
            self.openGallery()
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel){
            UIAlertAction in
        }

        // Add the actions
        picker.delegate = self
        alert.addAction(cameraAction)
        alert.addAction(galleryAction)
        alert.addAction(cancelAction)
    }

    func pickImage(_ viewController: UIViewController, _ callback: @escaping ((UIImage) -> ())) {
        pickImageCallback = callback;
        self.viewController = viewController;

        alert.popoverPresentationController?.sourceView = self.viewController!.view

        viewController.present(alert, animated: true, completion: nil)
    }
    func openCamera(){
        alert.dismiss(animated: true, completion: nil)
        if(UIImagePickerController .isSourceTypeAvailable(.camera)){
            picker.sourceType = .camera
            self.viewController!.present(picker, animated: true, completion: nil)
        } else {
            let alertController: UIAlertController = {
                let controller = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
                let action = UIAlertAction(title: "OK", style: .default)
                controller.addAction(action)
                return controller
            }()
            viewController?.present(alertController, animated: true)
        }
    }
    func openGallery(){
        alert.dismiss(animated: true, completion: nil)
        picker.sourceType = .photoLibrary
        self.viewController!.present(picker, animated: true, completion: nil)
    }

    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    //for swift below 4.2
    //func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    //    picker.dismiss(animated: true, completion: nil)
    //    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    //    pickImageCallback?(image)
    //}
    
    // For Swift 4.2+
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        guard let image = info[.originalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
        pickImageCallback?(image)
    }



    @objc func imagePickerController(_ picker: UIImagePickerController, pickedImage: UIImage?) {
    }

}

在您的视图控制器中像这样调用:

    ImagePickerManager().pickImage(self){ image in
        //here is the image
    }

同时不要忘记在你的info.plist中包含以下关键字:

<key>NSCameraUsageDescription</key>
<string>This app requires access to the camera.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>This app requires access to the photo library.</string>

2
不得不替换imagePickerController函数才能使其正常工作。谢谢! let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage pickImageCallback?(image) picker.dismiss(animated: true, completion: nil) }``` - Tum
2
'NSInternalInconsistencyException',原因:'UIAlertController 只能有一个样式为 UIAlertActionStyleCancel 的操作' 我在上面的代码中遇到了这个错误。 - PaFi
1
@Ing.Ron,addActions 只需要设置一次,因此它们应该放在 init 方法中 - 我已经更新了代码。如果您有任何问题,请告诉我。 - vir us
1
保留循环问题:viewController变量应该是弱引用。 - Edoardo Vicoli
如果您正在为iPad开发,请使用UIAlertController.Style.alert而不是.actionSheet,以避免在呈现UIAlertController(title: "Choose Image", message: nil, preferredStyle: .alert)时崩溃。 - Cory
显示剩余3条评论

43

对于Swift 3:

  1. First, you need to add the following key in info.plist:

        <key>NSPhotoLibraryUsageDescription</key>
    <string>This app requires access to the photo library.</string>
    
  2. Your View controller needs to conform to the following protocols: UIImagePickerControllerDelegate, UINavigationControllerDelegate:

    class ImagePickerViewController:  UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {}
    
  3. You need to declare the UIImage you will be useing to bind the returned/selected image:

    @IBOutlet weak var myImageView: UIImageView!
    @IBoutlet weak var upLoadImageBtn:UIImage!
    let imagePicker = UIImagePickerController()
    
  4. Set the pickerImage delegate to be your ViewController:

    imagePicker.delegate = self
    
  5. For the upload button, you will need to link to the following image in order to fire the action and display the image picker:

    @IBAction func upLoadImageBtnPressed(_ sender: AnyObject) {
        imagePicker.allowsEditing = false
        imagePicker.sourceType = .photoLibrary
    
    
        /*
        The sourceType property wants a value of the enum named        UIImagePickerControllerSourceType, which gives 3 options:
    
        UIImagePickerControllerSourceType.PhotoLibrary
        UIImagePickerControllerSourceType.Camera
        UIImagePickerControllerSourceType.SavedPhotosAlbum
    
        */
        present(imagePicker, animated: true, completion: nil)
    
    }
    
  6. Your View controller needs to implement the delegate methods for the image picker delegates:

    // MARK: - ImagePicker Delegate
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    
        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            myImageView.contentMode = .scaleAspectFit
            myImageView.image = pickedImage
        }
    
    
        /*
    
        Swift Dictionary named “info”.  
        We have to unpack it from there with a key asking for what media information we want.
        We just want the image, so that is what we ask for.  For reference, the available options are:
    
        UIImagePickerControllerMediaType
        UIImagePickerControllerOriginalImage
        UIImagePickerControllerEditedImage
        UIImagePickerControllerCropRect
        UIImagePickerControllerMediaURL
        UIImagePickerControllerReferenceURL
        UIImagePickerControllerMediaMetadata
    
        */
        dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion:nil)
    }
    

14
在 Swift 5 中,您必须执行此操作
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet var imageView: UIImageView!
    var imagePicker = UIImagePickerController()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func setPicture(_ sender: Any) {
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            imagePicker.delegate = self
            imagePicker.sourceType = .photoLibrary
            imagePicker.allowsEditing = false

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

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            imageView.image = image
        }

    }




}

13

我会为您提供最易懂的代码来选择图片,请参考以下内容:

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) 
{
     var alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
     var cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default)
     {
        UIAlertAction in
        self.openCamera()
     }
     var gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertActionStyle.Default)
     {
        UIAlertAction in
        self.openGallary()
     }
     var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel)
     {
        UIAlertAction in
     }

    // Add the actions
     picker?.delegate = self
     alert.addAction(cameraAction)
     alert.addAction(gallaryAction)
     alert.addAction(cancelAction)
     self.presentViewController(alert, animated: true, completion: nil)
}
func openCamera()
{
    if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
    {
        picker!.sourceType = UIImagePickerControllerSourceType.Camera
        self .presentViewController(picker!, animated: true, completion: nil)
    }
    else
    {
        let alertWarning = UIAlertView(title:"Warning", message: "You don't have camera", delegate:nil, cancelButtonTitle:"OK", otherButtonTitles:"")
        alertWarning.show()
    }
}
func openGallary()
{
    picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    self.presentViewController(picker!, animated: true, completion: nil)
}

//PickerView Delegate Methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
{
    picker .dismissViewControllerAnimated(true, completion: nil)
    imageView.image=info[UIImagePickerControllerOriginalImage] as? UIImage
}
func imagePickerControllerDidCancel(picker: UIImagePickerController)
{
    println("picker cancel.")
}

祝你有美好的一天 :-)


8
    @IBAction func chooseProfilePicBtnClicked(sender: AnyObject) {
    let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
    let cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default)
        {
            UIAlertAction in
            self.openCamera()
    }
    let gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertActionStyle.Default)
        {
            UIAlertAction in
            self.openGallary()
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel)
        {
            UIAlertAction in
    }

    // Add the actions
    picker.delegate = self
    alert.addAction(cameraAction)
    alert.addAction(gallaryAction)
    alert.addAction(cancelAction)
    self.presentViewController(alert, animated: true, completion: nil)
}
func openCamera(){
    if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){
        picker.sourceType = UIImagePickerControllerSourceType.Camera
        self .presentViewController(picker, animated: true, completion: nil)
    }else{
        let alert = UIAlertView()
        alert.title = "Warning"
        alert.message = "You don't have camera"
        alert.addButtonWithTitle("OK")
        alert.show()
    }
}
func openGallary(){
    picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    self.presentViewController(picker, animated: true, completion: nil)
}
//MARK:UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
    picker .dismissViewControllerAnimated(true, completion: nil)
    imageViewRef.image=info[UIImagePickerControllerOriginalImage] as? UIImage
}
func imagePickerControllerDidCancel(picker: UIImagePickerController){
    print("picker cancel.")
}

6

XCODE 10.1 / SWIFT 4.2 :

  1. 添加所需权限 (其他已提到)

  2. 将此类添加到您的视图中:


    import UIKit

    import Photos

    import Foundation

class UploadImageViewController: UIViewController, UIImagePickerControllerDelegate , UINavigationControllerDelegate {

        @IBOutlet weak var imgView: UIImageView!

        let imagePicker = UIImagePickerController()

        override func viewDidLoad() {

            super.viewDidLoad()

            checkPermission()

            imagePicker.delegate = self
            imagePicker.allowsEditing = false
            imagePicker.sourceType = .photoLibrary
        }

        @IBAction func btnSetProfileImageClickedCamera(_ sender: UIButton) {
        }

        @IBAction func btnSetProfileImageClickedFromGallery(_ sender: UIButton) {
            self.selectPhotoFromGallery()
        }

        func selectPhotoFromGallery() {
            self.present(imagePicker, animated: true, completion: nil)
        }

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

            if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
                    self.imgView.contentMode = .scaleAspectFit
                    self.imgView.image = pickedImage
                }

            dismiss(animated: true, completion: nil)
        }


        func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
            print("cancel is clicked")
        }


        func checkPermission() {
            let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
            switch photoAuthorizationStatus {
            case .authorized:
                print("Access is granted by user")
            case .notDetermined:
                PHPhotoLibrary.requestAuthorization({
                    (newStatus) in
                    print("status is \(newStatus)")
                    if newStatus ==  PHAuthorizationStatus.authorized {
                        /* do stuff here */
                        print("success")
                    }
                })
                print("It is not determined until now")
            case .restricted:
                // same same
                print("User do not have access to photo album.")
            case .denied:
                // same same
                print("User has denied the permission.")
            }
        }
    }

3

以下是显示照片库图像的Swift代码:

var pkcrviewUI = UIImagePickerController()
        if UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)
        {
            pkcrviewUI.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            pkcrviewUI.allowsEditing = true
            pkcrviewUI.delegate = self
            [self .presentViewController(pkcrviewUI, animated: true , completion: nil)]
        }

3

Xcode 10,Swift 4.2

以下是稍微优化过的实现版本。 这是使用Swift 4.2编写并测试过的。

您可以在这里查看ViewController的完整代码。 请注意,您还必须在Storyboard中定义IBOutlet(imageView)和IBAction(didTapOnChooseImageButton)并进行连接。希望这有所帮助。

import UIKit

class ImagePickViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

var imagePicker = UIImagePickerController()
@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

@IBAction func didTapOnChooseImageButton(_ sender: Any) {
    let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertController.Style.actionSheet)
    let cameraAction = UIAlertAction(title: "Camera", style: UIAlertAction.Style.default) {
        UIAlertAction in
        self.openCamera(UIImagePickerController.SourceType.camera)
    }
    let gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertAction.Style.default) {
        UIAlertAction in
        self.openCamera(UIImagePickerController.SourceType.photoLibrary)
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel) {
        UIAlertAction in
    }

    // Add the actions
    imagePicker.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
    alert.addAction(cameraAction)
    alert.addAction(gallaryAction)
    alert.addAction(cancelAction)
    self.present(alert, animated: true, completion: nil)
}

func openCamera(_ sourceType: UIImagePickerController.SourceType) {
    imagePicker.sourceType = sourceType
    self.present(imagePicker, animated: true, completion: nil)
}

//MARK:UIImagePickerControllerDelegate

func imagePickerController(_ picker: UIImagePickerController,
                                    didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    imageView.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
    imagePicker.dismiss(animated: true, completion: nil)
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    print("imagePickerController cancel")
}

}

欢迎来到 SO Nish!这里不鼓励仅提供代码的回答,因为它们无法解释问题是如何被解决的。请更新您的回答,包括解释您的代码是如何解决问题的 :) - Joel
非常感谢,@Joel。我已经根据您的建议更新了答案。 - Nish

3

对于Swift 4
这段代码对我有效!!

import UIKit


class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    @IBOutlet var imageView: UIImageView!
    @IBOutlet var chooseBuuton: UIButton!
    var imagePicker = UIImagePickerController()

    override func viewDidLoad() {
        super.viewDidLoad()
        imagePicker.delegate = self
    }
    @IBAction func btnClicked() {

    if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) 
    {
        print("Button capture")
        imagePicker.sourceType = .savedPhotosAlbum;
        imagePicker.allowsEditing = false

        self.present(imagePicker, animated: true, completion: nil)
        }
    }

  @objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
    imageView.image = chosenImage

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接