Swift版本: 3.0
代码
首先在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 ]
在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
完整demo百度云下载链接
原文地址:https://www.jb51.cc/swift/322983.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。