Swift - 从相册中选择视频(过滤掉照片,使用UIImagePickerController)
Posted sundaysme
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift - 从相册中选择视频(过滤掉照片,使用UIImagePickerController)相关的知识,希望对你有一定的参考价值。
(本文代码已升级至Swift4)
有时我们需要从系统相册中选择视频录像,来进行编辑或者上传操作,这时使用 UIImagePickerController 就可以实现。
默认情况下,UIImagePickerController 打开系统“照片”后允许用户选择所有的媒体文件(不管是照片还是录像),我们可以通过 mediaTypes 属性设置。让其只显示视频录像。
1,样例说明
(1)下面样例点击“选择视频”按钮后,会自动打开相册选择视频。
(2)由于设置了 mediaTypes,所有的图片都会过滤掉,只留下视频选择。
(3)选择完毕,系统会自动将视频复制一个到应用的 tmp 文件夹(临时文件夹)下。我们可以直接对这个文件进行操作,而不会影响到系统相册中的原视频。
(4)本样例选择后,就直接使用 AVPlayerViewController 进行播放。
2,效果图
可以看到选择后,视频会被复制到 tmp 目录下:
选择完毕后自动播放该视频:
3,样例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
import UIKit import MobileCoreServices import AssetsLibrary import AVKit import AVFoundation
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
override func viewDidLoad() { super.viewDidLoad()
//创建一个ContactAdd类型的按钮 let button:UIButton = UIButton(type:.system) button.frame = CGRect(x:10, y:150, width:100, height:30) button.setTitle("选择视频", for:.normal) button.addTarget(self, action:#selector(selectVideo), for:.touchUpInside) self.view.addSubview(button) }
//选择视频 @objc func selectVideo() { if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { //初始化图片控制器 let imagePicker = UIImagePickerController() //设置代理 imagePicker.delegate = self //指定图片控制器类型 imagePicker.sourceType = .photoLibrary //只显示视频类型的文件 imagePicker.mediaTypes = [kUTTypeMovie as String] //不需要编辑 imagePicker.allowsEditing = false //弹出控制器,显示界面 self.present(imagePicker, animated: true, completion: nil) } else { print("读取相册错误") } }
//选择视频成功后代理 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { //获取视频路径(选择后视频会自动复制到app临时文件夹下) let videoURL = info[UIImagePickerControllerMediaURL] as! URL let pathString = videoURL.relativePath print("视频地址:(pathString)")
//图片控制器退出 self.dismiss(animated: true, completion: {})
//播放视频文件 reviewVideo(videoURL) }
//视频播放 func reviewVideo(_ videoURL: URL) { //定义一个视频播放器,通过本地文件路径初始化 let player = AVPlayer(url: videoURL) let playerViewController = AVPlayerViewController() playerViewController.player = player self.present(playerViewController, animated: true) { playerViewController.player!.play() } }
override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } |
原文出自:www.hangge.com 转载请保留原文链接:http://www.hangge.com/blog/cache/detail_1192.html
一、介绍
图片选择或者拍照功能:
1、选择相册中的图片或是拍照,都是通过UIImagePickerController控制器实例化一个对象,然后通过self.presentViewController方法推出界面显示。但是使用presentViewController的类需要实现UIImagePickerControllerDelegate、UINavigationController两个代理。
2、UIImagePickerController可以通过isSourceTypeAvailable方法来判断设备是否支持照相机/图片库/相册功能。如果支持,可以通过sourceType属性来设置图片控制器的显示类型。类型一共分为3种:PhotoLibrary(照片库)、Camera(相机)、SavedPhotoAlbum(相册)
3、实现协议截图
二、实例
1、使用相册选择步骤:
- 判断是否支持要使用的图片库或相册功能
- 初始化图片控制器对象
- 指定图片控制器对象的代理
- 指定图片控制器的类型,前提是必须先导入MobileCoreServices.framework框架
- 弹出显示图片控制器
- 实现图片控制住器代理方法
func chooseImageFromAlbum(){
//判断是否支持要使用的图片库
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
//初始化图片控制器
let picker = UIImagePickerController()
//设置代理
picker.delegate = self
//设置媒体类型
picker.mediaTypes = [kUTTypeImage as String,kUTTypeVideo as String]
//设置允许编辑
picker.allowsEditing = true
//指定图片控制器类型
picker.sourceType = .photoLibrary
//弹出控制器,显示界面
self.present(picker, animated: true, completion: nil)
}
else{
let alert = UIAlertView.init(title: "读取相册错误!", message: nil, delegate: nil, cancelButtonTitle: "确定")
alert.show()
}
}
//实现图片控制器代理方法
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//查看info对象
print(info)
//获取选择的原图
let originImage = info[UIImagePickerControllerOriginalImage] as! UIImage
//赋值,图片视图显示图片
self.pickerView.image = originImage
//图片控制器退出
picker.dismiss(animated: true, completion: nil)
}
//取消图片控制器代理
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
//图片控制器退出
picker.dismiss(animated: true, completion: nil)
}
2、拍照步骤:
- 判断是否支持拍照功能
- 初始化图片控制器对象(可以设置是否允许编辑)
- 指定图片控制器对象的代理
- 指定图片控制器的类型
- 弹出显示图片控制器
func takePhotoFromCamera() {
//判断是否支持相机
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
//初始化图片控制器
let picker = UIImagePickerController()
//设置代理
picker.delegate = self
//设置媒体类型
picker.mediaTypes = [kUTTypeImage as String,kUTTypeVideo as String]
//设置来源
picker.sourceType = UIImagePickerControllerSourceType.camera
//设置镜头 front:前置摄像头 Rear:后置摄像头
if UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.front) {
picker.cameraDevice = UIImagePickerControllerCameraDevice.front
}
//设置闪光灯(On:开、Off:关、Auto:自动)
picker.cameraFlashMode = UIImagePickerControllerCameraFlashMode.on
//允许编辑
picker.allowsEditing = true
//打开相机
self.present(picker, animated: true, completion: nil)
}
else{
let alert = UIAlertView.init(title: "找不到相机!", message: nil, delegate: nil, cancelButtonTitle: "确定")
alert.show()
}
}
程序猿神奇的手,每时每刻,这双手都在改变着世界的交互方式!
//
// ViewController.swift
// SwiftExample
//
// Created by administrator on 2019/2/15.
// Copyright ? 2019 administrator. All rights reserved.
//
import UIKit
import AVFoundation
import MobileCoreServices
import AssetsLibrary
import AVKit
class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
func isCameraAvailable() -> Bool {
return UIImagePickerController.isSourceTypeAvailable(.camera)
}
func cameraSuportsMedia(mediaType:String, sourceType: UIImagePickerController.SourceType) -> Bool {
let availabelMediaTypes = UIImagePickerController.availableMediaTypes(for: sourceType)
for type in availabelMediaTypes! {
if type == mediaType{
return true
}
}
return false
}
func doesCameraSupportShootingVideos() -> Bool {
return cameraSuportsMedia(mediaType: (kUTTypeMovie as NSString) as String, sourceType: .camera)
}
func doesCameraSupportTakingPhotos() -> Bool {
return cameraSuportsMedia(mediaType: (kUTTypeImage as NSString) as String, sourceType: .camera)
}
func isFrontCameraAvailable() -> Bool {
return UIImagePickerController.isCameraDeviceAvailable(.front)
}
func isRearCameraAvailable() -> Bool {
return UIImagePickerController.isCameraDeviceAvailable(.rear)
}
func isFlashAvailableOnFrontCamera() -> Bool {
return UIImagePickerController.isFlashAvailable(for: .front)
}
func isFlashAvailableOnRearCamera() -> Bool {
return UIImagePickerController.isFlashAvailable(for: .rear)
}
//确定视图控制器的ViewDidAppear方法是否被调用,如果没有则展示拍照视图
var beenhereBefore = false
var imagePickerController :UIImagePickerController?
override func viewDidAppear(_ animated: Bool) {
if beenhereBefore {
//viewDidapear方法无论何时,在视图控制器展现时都会被调用,设置此值,控制器只展示一次
return
} else {
beenhereBefore = true
}
if isCameraAvailable() && doesCameraSupportTakingPhotos() {
imagePickerController = UIImagePickerController()
if let theController = imagePickerController{
theController.sourceType = .camera
theController.mediaTypes = [kUTTypeImage as NSString, kUTTypeVideo as NSString] as [String]
// theController.mediaTypes = [kUTTypeVideo as NSString] as [String]
theController.allowsEditing = true
theController.delegate = self
present(theController, animated: true) {
}
}
} else {
print("Camera is not available")
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let mediaType = info[.mediaType]
if let type:AnyObject = mediaType as AnyObject{
if type is String{
if let stringType :String = type as! String {
if stringType as NSString == kUTTypeVideo as NSString {
let urlOfVideo = info[.mediaURL] as! NSURL
if let url:NSURL = urlOfVideo{
print("rul (url)")
}
}
if stringType as NSString == kUTTypeImage as NSString{
if let metadata = info[.mediaMetadata]{
let image = info[.originalImage] as! UIImage
if let theImage:UIImage = image{
print("image MetaData (metadata)")
print("(theImage)")
}
}
}
}
}
}
}
}
swift3 访问相册和摄像头
2017年05月10日 11:07:11 EIamor 阅读数:1245
版权声明:hahahaha , 努力 ing https://blog.csdn.net/EIamor/article/details/71515771
第一步:需要在项目中的Info.plist中添加相应的键
访问相册:Privacy - Photo Library Usage Description
访问摄像头:Privacy - Camera Usage Description
它们对应的值可以随意填写,但是其值是显示给用户的信息
第二步:请求访问
***注意:如果用button设置接收图片,则此button的类型不能为系统样式,即 addImageBtn.buttonType = .system 是无法设置成功的。 求大手告诉原因~~
这个例子中一整个图片添加是一个Button点击触发选择图片事件
首先要遵守UIImagePickerControllerDelegate,和UINavigationControllerDelegate
然后在button点击触发的事件中添加如下代码
@IBAction func chosePhoto(_ sender: UIButton) {
guard UIImagePickerController.isSourceTypeAvailable(.photoLibrary)else{ //如果是要访问相机只需要将.photoLibrary改为.camera即可
print("无法获得相册授权")
return
}
let picker = UIImagePickerController()
picker.allowsEditing = false //不允许编辑图片
picker.sourceType = .photoLibrary //选择器访问的是相册(如果是访问相机则将.photoLibrary改为.camera)
picker.delegate = self //设置代理
self.present(picker, animated: true, completion: nil)//以模态视图弹出选择器
}
guard 的作用是保证应用获得用户授权之后才能访问相册
第三步:访问完相册之后就要让在相册中被点击的图片设置为Button的图片
//必须要先设置picker的代理
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//被点击的图片的信息保存在info字典中
self.albumBtn.setImage(info[UIImagePickerControllerOriginalImage] as? UIImage, for: .normal)
self.albumBtn.imageView?.contentMode = .scaleAspectFill
self.albumBtn.imageView?.clipsToBounds = true
dismiss(animated: true, completion: nil)
}
结果:
5.15更新****************************************
之前的版本里在打开相册的时候只能选择图片而不能选择视频,这是因为UIImagePickerViewController.mediaTypes为设置,当mediaTypes没设置的时候默认为kUTTypeImage ,即:只选择图片
所以当要选择视频的时候只需要将mediaTypes 设置为 kUTTypeMovie即可
例:
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
picker.sourceType = .photoLibrary
picker.mediaTypes = [kUTTypeMovie as String , kUTTypeImage as String] //可以选择视频和图片
present(picker, animated: true, completion: nil)
然后在 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])方法中判断选择的是图片还是视频之后在做需要做的操作
例:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let type = info[UIImagePickerControllerMediaType] as? String //获取所选中项目的类型
if type == kUTTypeMovie as String{ //判断选中的是图片还是视频
let videoURL = info[UIImagePickerControllerMediaURL] as! NSURL
self.dismiss(animated: true, completion: nil)
//写出你要做的操作,我这里的示例是做的共享的操作
let activityViewController = UIActivityViewController(activityItems: [videoURL], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}else{
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
self.selectedImage = image
self.dismiss(animated: true, completion: nil)
let shareVC = UIActivityViewController(activityItems: [image], applicationActivities: nil)
shareVC.popoverPresentationController?.sourceView = self.view
present(shareVC, animated: true, completion: nil)
}
}
以上是关于Swift - 从相册中选择视频(过滤掉照片,使用UIImagePickerController)的主要内容,如果未能解决你的问题,请参考以下文章
允许用户从相机、照片库或相册中选择图像并遇到我无法解决的错误