Swift 打开图库

Swift版本: 3.0

代码

  1. 首先在info.plist内添加两个参数如下,给足权限,否则无法打开图库

    Key : Privacy - Media Library Usage Description
    Value : YES  [ It is not boolean,it is String ]
    
    Key : Privacy - Photo Library Usage Description
    Value : YES [ It is not boolean,it is String ]
  2. 在ViewController中改为如下代码

    import UIKit
    // 首先在头部加入当前Controller需要遵从的代理
    class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    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.
    }
    
    // 创建一个对象
    // 这个对象是用来在屏幕上显示
    @IBOutlet weak var imagePicked: UIImageView!
    // 这个Action方法对应着屏幕上的按钮,该按钮点击后会调用图库
    @IBAction func add(_ sender: UIBarButtonItem) {
    // 判断数据源是否合法,这里的.photoLibrary省略了其类名,Swift会自动推导
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .photoLibrary
            imagePicker.allowsEditing = true
            // 这一句,开始调用图库
            self.present(imagePicker,animated: true)
        }
    }
    // 实现代理的方法
    // 注意,这里和swift3.0之前的版本实现方法都不太一样,这是唯一的写法,网上流传的其他方法都是过时的
    
    func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediawithInfo info: [String : Any]) {
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
        // 将图片显示给UIImageView
            imagePicked.image = image
        }else{
            print("pick image wrong")
        }
        // 收回图库选择界面
        self.dismiss(animated: true,completion: nil)
    }
    }

实际效果


打开图库


显示到界面

参考:
http://stackoverflow.com/questions/37925583/uiimagepickercontroller-crashes-app-swift3-xcode8

http://stackoverflow.com/questions/39009889/xcode-8-creating-an-image-format-with-an-unknown-type-is-an-error

完整demo百度云下载链接

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...