ios 如何允许用户使用 Swift 选择图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25510081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to allow user to pick the image with Swift?
提问by LA_
I am writing my first iOS application (iPhone only) with Swift. The main application view should allow user to choose the image from the photo gallery.
我正在使用 Swift 编写我的第一个 iOS 应用程序(仅限 iPhone)。主应用程序视图应允许用户从照片库中选择图像。
I've found the following sample code of ViewController.swift:
我找到了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)
}
}
and have the following View Controller Scene -
并有以下视图控制器场景 -
View Controller
- Top Layout Guide
- Bottom Layout Guide
- View
- Image View
First Responder
Exit
But when I start the app, just black screen is shown. What I am doing wrong? Another sample codeI've found is in Objective-C, which doesn't help me.
但是当我启动应用程序时,只显示黑屏。我做错了什么?我发现的另一个示例代码是在 Objective-C 中,它对我没有帮助。
回答by Dekel Maman
If you just want let the user choose image with UIImagePickerController use this code:
如果您只想让用户使用 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
}
}
回答by vir us
Complete copy-paste working image picker for swift 4based on @user3182143 answer:
基于@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)
}
//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?) {
}
}
Call it from your viewcontroller like this:
从您的视图控制器中调用它,如下所示:
ImagePickerManager().pickImage(self){ image in
//here is the image
}
Also don't forget to include the following keys in your info.plist
:
也不要忘记在您的 中包含以下键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>
回答by Amr Angry
For Swift 3:
对于 Swift 3:
First, you need to add the following key in info.plist:
<key>NSPhotoLibraryUsageDescription</key> <string>This app requires access to the photo library.</string>
Your View controller needs to conform to the following protocols:
UIImagePickerControllerDelegate
,UINavigationControllerDelegate
:class ImagePickerViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {}
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()
Set the pickerImage delegate to be your ViewController:
imagePicker.delegate = self
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) }
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) }
首先,您需要在 info.plist 中添加以下键:
<key>NSPhotoLibraryUsageDescription</key> <string>This app requires access to the photo library.</string>
您的视图控制器需要符合以下协议:
UIImagePickerControllerDelegate
,UINavigationControllerDelegate
:class ImagePickerViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {}
您需要声明将用于绑定返回/选定图像的 UIImage:
@IBOutlet weak var myImageView: UIImageView! @IBoutlet weak var upLoadImageBtn:UIImage! let imagePicker = UIImagePickerController()
将 pickerImage 委托设置为您的 ViewController:
imagePicker.delegate = self
对于上传按钮,您需要链接到以下图像以触发操作并显示图像选择器:
@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) }
您的视图控制器需要为图像选择器委托实现委托方法:
// 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) }
回答by user3182143
I will give you best understandable coding for pick the image,refer this
我会给你最容易理解的编码来选择图像,参考这个
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.")
}
Have a nice day:-)
祝你今天过得愉快:-)
回答by Mannam Brahmam
@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.")
}
回答by FRIDDAY
XCODE 10.1 / SWIFT 4.2 :
XCODE 10.1/SWIFT 4.2:
Add required permissions (others mentioned)
Add this class to your view:
添加所需的权限(其他提到的)
将此类添加到您的视图中:
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.")
}
}
}
回答by Jamil Hasnine Tamim
For Swift 4
This code working for me!!
对于 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)
}
}
回答by NRV
Do this stuff for displaying photo library images swift coding:
执行以下操作以快速编码显示照片库图像:
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)]
}
回答by Rachel Harvey
I know this is question is a year old, but here's some pretty simple code (mostly from this tutorial) that's working well for me:
我知道这个问题已经有一年了,但这里有一些非常简单的代码(主要来自本教程),对我来说效果很好:
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
var imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
self.imagePicker.delegate = self
}
@IBAction func loadImageButtonTapped(sender: AnyObject) {
print("hey!")
self.imagePicker.allowsEditing = false
self.imagePicker.sourceType = .SavedPhotosAlbum
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.imageView.contentMode = .ScaleAspectFit
self.imageView.image = pickedImage
}
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
self.imagePicker = UIImagePickerController()
dismissViewControllerAnimated(true, completion: nil)
}
回答by Siddharth Kavthekar
Of course, above answers solve the main problem.
当然,以上答案解决了主要问题。
I faced a crash in Swift 3.0 while launching the photo album because Info.plist did not had these flags:
我在 Swift 3.0 中启动相册时遇到了崩溃,因为 Info.plist 没有这些标志:
Privacy - Photo Library Usage Description -> NSPhotoLibraryUsageDescription
Privacy - Camera Usage Description -> NSCameraUsageDescription
隐私 - 照片库使用说明 -> NSPhotoLibraryUsageDescription
隐私 - 相机使用说明 -> NSCameraUsageDescription
[
[
Please add them if you face similar issue.
如果您遇到类似问题,请添加它们。
Thanks !
谢谢 !