使用 Swift 从 iOS 中的 PhotoLibrary 中选择视频

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30715212/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:16:00  来源:igfitidea点击:

Select video from PhotoLibrary in iOS using Swift

iosswiftuiimagepickercontrollermediatypemobilecoreservices

提问by NKurapati

I am trying to select video from PhotoLibrary using following code

我正在尝试使用以下代码从 PhotoLibrary 中选择视频

imageController.mediaTypes = [kUTTypeMovie: NSString]

After selecting video, when it is compressing, I am getting array out of boundary issue.

选择视频后,在压缩时,出现数组越界问题。

I searched online and found following line. I am unable to convert it into Swift version (link) imageController.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil]

我在网上搜索并找到了以下行。我无法将其转换为 Swift 版本(链接imageController.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil]

Please let us know the Swift version for above line. It is very useful if anyone can provide Swift version of this.

请让我们知道上述行的 Swift 版本。如果有人可以提供 Swift 版本,将非常有用。

Question2:

问题2

I want to show selected video in app and need to play when it is tapped. Can we do it without external plugins and using built in libraries?

我想在应用程序中显示选定的视频,需要在点击时播放。我们可以在没有外部插件并使用内置库的情况下做到这一点吗?

回答by XueYu

Based on Swift 2.2

基于 Swift 2.2

Suppose you have a imagePickerController and when you want to select both images and videos:

假设您有一个 imagePickerController 并且当您想要同时选择图像和视频时:

let imagePickerController = UIImagePickerController()
var videoURL: NSURL?    

@IBAction func selectImageFromPhotoLibrary(sender: UIBarButtonItem) {
  imagePickerController.sourceType = .PhotoLibrary
  imagePickerController.delegate = self
  imagePickerController.mediaTypes = ["public.image", "public.movie"]

  presentViewController(imagePickerController, animated: true, completion: nil)    
}

Then after the video is selected, print out its NSURL.

然后选择视频后,打印出它的NSURL。

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
  videoURL = info["UIImagePickerControllerReferenceURL"] as? NSURL
  print(videoURL)
  imagePickerController.dismissViewControllerAnimated(true, completion: nil)
}

For question 2:

对于问题 2:

Yes, you can do it through AVPlayer, you need import AVKit and AVFoundation, and you code may look like this:

是的,您可以通过 AVPlayer 来完成,您需要导入 AVKit 和 AVFoundation,您的代码可能如下所示:

if let videoURL = videoURL{
  let player = AVPlayer(URL: videoURL)

  let playerViewController = AVPlayerViewController()
  playerViewController.player = player

  presentViewController(playerViewController, animated: true) {
    playerViewController.player!.play()
  }
}

I made a demohere you can refer, maybe not 100% what you want.

我在这里做了一个演示,你可以参考,也许不是你想要的 100%。

回答by Aayushi

@IBOutlet weak var imgView: UIImageView!
var imagePickerController = UIImagePickerController()
var videoURL : NSURL?

@IBAction func btnSelectVideo_Action(_ sender: Any) {
    imagePickerController.sourceType = .savedPhotosAlbum
    imagePickerController.delegate = self
    imagePickerController.mediaTypes = [kUTTypeMovie as String]
    present(imagePickerController, animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    videoURL = info[UIImagePickerControllerMediaURL]as? NSURL
    print(videoURL!)
    do {
        let asset = AVURLAsset(url: videoURL as! URL , options: nil)
        let imgGenerator = AVAssetImageGenerator(asset: asset)
        imgGenerator.appliesPreferredTrackTransform = true
        let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil)
        let thumbnail = UIImage(cgImage: cgImage)
        imgView.image = thumbnail
    } catch let error {
        print("*** Error generating thumbnail: \(error.localizedDescription)")
    }
    self.dismiss(animated: true, completion: nil)
}

For question 2:

对于问题 2:

let player = AVPlayer(url: videoURL)
let playerController = AVPlayerViewController()
playerController.player = player
self.present(playerController, animated: true) {
    player.play()

}

回答by Giang

Swift 3

斯威夫特 3

import MobileCoreServices

var imagePickerController = UIImagePickerController()
var videoURL: URL?

private func openImgPicker() {
    imagePickerController.sourceType = .savedPhotosAlbum
    imagePickerController.delegate = self
    imagePickerController.mediaTypes = ["public.movie"]
    present(imagePickerController, animated: true, completion: nil)
}

extension YourViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        videoURL = info[UIImagePickerControllerMediaURL] as? URL
        print("videoURL:\(String(describing: videoURL))")
        self.dismiss(animated: true, completion: nil)
    }
}

回答by Shakeel Ahmed

Swift 5+ solution:

Swift 5+ 解决方案:

func openVideoGallery() {
    picker = UIImagePickerController()
    picker.delegate = self
    picker.sourceType = .savedPhotosAlbum
    picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .savedPhotosAlbum)!
    picker.mediaTypes = ["public.movie"]      
    picker.allowsEditing = false
    present(picker, animated: true, completion: nil)
}

回答by bluemobi

func openCamera() {
  if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
    println("captureVideoPressed and camera available.")

    var imagePicker = UIImagePickerController()

    imagePicker.delegate = self
    imagePicker.sourceType = .Camera
    imagePicker.mediaTypes = [kUTTypeMovie!]
    imagePicker.allowsEditing = false

    imagePicker.showsCameraControls = true

    self.presentViewController(imagePicker, animated: true, completion: nil)   
  } else {
    println("Camera not available.")
  }  
}

func imagePickerController(  didFinishPickingMediaWithInfo info:NSDictionary!) {
  videoUrl = info[UIImagePickerControllerMediaURL] as! NSURL!
  let pathString = videoUrl.relativePath
  self.dismissViewControllerAnimated(true, completion: nil)
}

回答by V.Kumar

Swift 4.0

斯威夫特 4.0

Your class adopts the UIImagePickerControllerDelegate protocol

你的类采用 UIImagePickerControllerDelegate 协议

class classname: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate

After that you need to create

之后你需要创建

let imagePickerController = UIImagePickerController()

Add this in your button's action:-

将此添加到您按钮的操作中:-

imagePickerController.sourceType = .photoLibrary

imagePickerController.delegate = self

imagePickerController.mediaTypes = ["public.image", "public.movie"]

present(imagePickerController, animated: true, completion: nil)

Delegate method

委托方法

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

 let videoURL = info["UIImagePickerControllerReferenceURL"] as? NSURL
 print(videoURL!)
 imagePickerController.dismiss(animated: true, completion: nil)
}

回答by AiU

try this pod that i've made :

试试我做的这个豆荚:

https://github.com/jhonyourangel/ImagePickerWhatsApp

I was searching for a similar Image and Video Picker for a project and i wasn't able to find one that was able to : 1. Take picture 2. Get a Picture from the library 3. Register a Video 4. Get a video from the library

我正在为一个项目寻找类似的图像和视频选择器,但我找不到能够: 1. 拍照 2. 从库中获取图片 3. 注册视频 4. 从以下位置获取视频图书馆

While i was looking i hopen whatsup of facebook or mabe google have a pod for this kind of needs, i realy liked the whatsapp picker, so i created this one similer to the one in whatsapp.

当我在寻找时,我希望 facebook 或 mabe google 的 whatsup 有一个可以满足这种需求的豆荚,我真的很喜欢 whatsapp 选择器,所以我创建了这个类似于 whatsapp 中的那个。

Prerequisites

先决条件

In order to use ImageVideoPicker you need cocoapods and an xCode project already created

为了使用 ImageVideoPicker 你需要 cocoapods 和一个已经创建的 xCode 项目

Installing

安装

to install cocoapods is should be enough just to run sudo gem install cocoapodsin the terminal if this doen't work go to cocoapods

安装 cocoapods 应该足以sudo gem install cocoapods在终端中运行,如果这不起作用,请转到cocoapods

Then navigate the terminal to your project folder, where the file extension .xcodeprojis located and run pod initthis will create a file called PodfileOpen the file in a editor ( sublimeText, xCode, atom, vim ... etc ) and add the line bellow after use_frameworks!

然后将终端导航到您的项目文件夹,文件扩展名.xcodeproj所在的位置并运行pod init这将创建一个名为PodfileOpen the file in a editor (sublimeText, xCode, atom, vim ... etc ) 并在后面添加以下行use_frameworks!

pod 'ImagePickerWhatsApp'

or pod 'ImagePickerWhatsApp', :path => '/Users/aiu/Documents/cocoapods/ImagePickerWhatsApp'

或 pod 'ImagePickerWhatsApp', :path => '/Users/aiu/Documents/cocoapods/ImagePickerWhatsApp'

then just run pod installin the terminal and wait to finish instaling the lib

然后只需pod install在终端中运行并等待完成安装 lib

How to use it

如何使用它

add import ImagePickerWhatsAppto your viewcontroller class

添加import ImagePickerWhatsApp到您的视图控制器类

then you can call the picker by calling : let mp = ImageVideoPicker.makeVCFromStoryboard() self.present(mp, animated: true, completion: nil)

然后你可以通过调用来调用选择器: let mp = ImageVideoPicker.makeVCFromStoryboard() self.present(mp, animation: true, completion: nil)

Delegate

代表

to implement the delegate add mp.delegate = selfand the extent the class of you view controller aso you need to import the iOS Photos framework import Photos

要实现委托添加mp.delegate = self和视图控制器类的范围,您需要导入 iOS 照片框架import Photos

extension ViewController: ImageVideoPickerDelegate {
    func onCancel() {
        print("no picture selected")
    }

    func onDoneSelection(assets: [PHAsset]) {
       print("selected \(assets.count) assets")
    }
}

the func onDoneSelectionreturns an array of assets that contain the info of where the asset is located : on the device, iTunes library or iCloud.

funconDoneSelection返回一个包含资产位置信息的资产数组:在设备、iTunes 库或 iCloud 上。

if you just need to display the images you can use the this code in a collection view or something similar just implement this peace of code

如果您只需要显示图像,您可以在集合视图中使用此代码或类似的东西,只需实现这种代码的和平

var representedAssetIdentifier: String!

func getImageFrom(asset: Phasset) {
     representedAssetIdentifier = asset?.localIdentifier
    let imageManager = PHCachingImageManager()

    imageManager.requestImage(for: asset!, targetSize: self.frame.size, contentMode: .default, options: nil) { (image, _) in

        if(self.representedAssetIdentifier == self.asset?.localIdentifier &&
             image != nil) {
             self.imageView.image = image
        }
    }
}

this will show just the thumbnail, but is awesome because is also showing the thumbnail for live photos, and videos

这将只显示缩略图,但很棒,因为它还显示了实时照片和视频的缩略图

Images and Videos as Data

图像和视频作为数据

The lib is intended to be used for sending images or videos over the network, and not to do fancy image or video editing. But this doesn't mea you can't. You can do just about anything since it returns an array of assets, but is you job to implement what you need.

该库旨在用于通过网络发送图像或视频,而不是进行花哨的图像或视频编辑。但这并不意味着你不能。你可以做任何事情,因为它返回一组资产,但你的工作是实现你需要的东西。

in order to get the data from the asset ImageVideoPicker has one method that will return an completition handler with the data.

为了从资产中获取数据,ImageVideoPicker 有一种方法可以返回一个包含数据的完成处理程序。

ImageVideoPicker.getDataFrom(asset: asset) { (data) in
    if data == nil {
        print(data as Any, asset.mediaType, asset.localIdentifier)
    } else {
        print(data!.count as Any, asset.mediaType, asset.localIdentifier)
    }
}

that will be all have fun

那会很有趣

回答by V.Kumar

Select a Video from Gallery using Swift 4

使用 Swift 4 从图库中选择视频

    // Put this code where you want to pick the video from gallery
    Let imagePickerController = UIImagePickerController ()
    imagePickerController.sourceType = .photoLibrary
    imagePickerController.delegate = self
    imagePickerController.mediaTypes = ["public.movie"]
    present(imagePickerController, animated: true, completion: nil)

    // UIImagePickerController Delegate Method
    func imagePickerController (_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) 
    {
         let videoURL = info[UIImagePickerControllerMediaURL] as? NSURL
         print(videoURL!)
         self.dismiss(animated: true, completion: nil)
    }

回答by Shanmugasundharam

if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
  println("Camera Available")
  var imagePicker = UIImagePickerController()
  imagePicker.delegate = self
  imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
  imagePicker.allowsEditing = false
  self.presentViewController(imagePicker, animated: true, completion: nil)
}

Delegate method

委托方法

func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) {
  self.dismissViewControllerAnimated(true, completion: nil)
  imageView.image = image
}

回答by force1Jai

func startMediaBrowserFromViewController(viewController: UIViewController!, usingDelegate delegate : protocol<UINavigationControllerDelegate, UIImagePickerControllerDelegate>!) -> Bool {
  if UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) == false {
    return false
  }
  let mediaUI = UIImagePickerController()
  mediaUI.sourceType = .SavedPhotosAlbum
  mediaUI.mediaTypes = [kUTTypeMovie as String]
  mediaUI.allowsEditing = true
  mediaUI.delegate = delegate
  presentViewController(mediaUI, animated: true, completion: nil)
  return true
}