如何让用户使用Swift选择图像?

LA_*_*LA_ 69 uiimagepickercontroller ios swift

我正在用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)
    }

}
Run Code Online (Sandbox Code Playgroud)

并具有以下视图控制器场景 -

View Controller
 - Top Layout Guide
 - Bottom Layout Guide
 - View
   - Image View
First Responder
Exit
Run Code Online (Sandbox Code Playgroud)

但是当我启动应用程序时,只显示黑屏.我做错了什么?我发现的另一个示例代码是Objective-C,它对我没有帮助.

Dek*_*man 111

如果您只是想让用户使用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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我赞成了bc,这真的很有帮助.只需将NSDictionary更改为[NSObject:AnyObject]并且效果很好! (3认同)

vir*_* us 57

基于@ 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()
    }

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

        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)
        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 alertWarning = UIAlertView(title:"Warning", message: "You don't have camera", delegate:nil, cancelButtonTitle:"OK", otherButtonTitles:"")
            alertWarning.show()
        }
    }
    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)
    }

    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?) {
    }

}
Run Code Online (Sandbox Code Playgroud)

从你的viewcontroller中调用它,如下所示:

    ImagePickerManager().pickImage(self){ image in
        //here is the image
    }
Run Code Online (Sandbox Code Playgroud)

另外,请不要忘记在您的密码中包含以下密钥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>
Run Code Online (Sandbox Code Playgroud)

  • 必须用它替换func`imagePickerController`使其起作用。谢谢!```func imagePickerController(_ picker:UIImagePickerController,didFinishPickingMediaWithInfo info:[UIImagePickerController.InfoKey:Any]){让image = info [UIImagePickerController.InfoKey.originalImage]为!UIImage pickImageCallback?(图像)picker.dismiss(动画:true,完成:无)}``` (2认同)
  • 'NSInternalInconsistencyException', reason: 'UIAlertController can only have an action with a style of UIAlertActionStyleCancel' 我在上面的代码中得到这个错误。 (2认同)

Amr*_*gry 33

对于Swift 3

1-首先,您需要在info.plist中添加以下密钥

    <key>NSPhotoLibraryUsageDescription</key>
<string>This app requires access to the photo library.</string>
Run Code Online (Sandbox Code Playgroud)

2-您的View Controller需要符合以下协议UIImagePickerControllerDelegate,UINavigationControllerDelegate.

class ImagePickerViewController:  UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {}
Run Code Online (Sandbox Code Playgroud)

3 - 需要声明您将用于绑定返回/选定图像的UIImage

  @IBOutlet weak var myImageView: UIImageView!
  @IBoutlet weak var upLoadImageBtn:UIImage!
  let imagePicker = UIImagePickerController()
Run Code Online (Sandbox Code Playgroud)

4-将pickerImage Delegate设置为ViewController

 imagePicker.delegate = self
Run Code Online (Sandbox Code Playgroud)

5-对于上传按钮,您需要喜欢以下图像才能触发操作并显示图像选择器

@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)

}
Run Code Online (Sandbox Code Playgroud)

6-您的View Controller需要为图像选择器委托实现委托方法

 // 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)
}
Run Code Online (Sandbox Code Playgroud)

祝你有美好的一天:)


use*_*143 12

我会给你最好的可理解的编码选择图像,参考这个

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.")
}
Run Code Online (Sandbox Code Playgroud)

祝你今天愉快:-)


小智 11

在 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
        }

    }




}
Run Code Online (Sandbox Code Playgroud)


Man*_*mam 7

    @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.")
}
Run Code Online (Sandbox Code Playgroud)


FRI*_*DAY 5

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.")
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)