22

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

imageController.mediaTypes = [kUTTypeMovie: NSString]

选择视频后,在压缩时,我遇到了数组超出边界的问题。

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

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

问题2

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

4

11 回答 11

34

Based on Swift 2.2

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

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.

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

For question 2:

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

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 demo here you can refer, maybe not 100% what you want.

于 2016-06-20T21:22:31.693 回答
17
@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)
}

对于问题 2:

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

}
于 2017-04-07T07:58:27.383 回答
14

Swift 5+ 解决方案:

func openVideoGallery() {
    picker = UIImagePickerController()
    picker.delegate = self
    picker.sourceType = .savedPhotosAlbum
    picker.mediaTypes = ["public.movie"]      
    picker.allowsEditing = false
    present(picker, animated: true, completion: nil)
}
于 2019-04-04T12:39:55.180 回答
12

斯威夫特 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)
    }
}
于 2017-07-21T03:16:37.853 回答
3
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)
}
于 2015-06-08T18:32:13.130 回答
3

使用 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)
    }
于 2018-10-25T07:58:01.677 回答
2

斯威夫特 4.0

您的班级采用 UIImagePickerControllerDelegate 协议

class classname: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate

之后,您需要创建

let imagePickerController = UIImagePickerController()

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

imagePickerController.sourceType = .photoLibrary

imagePickerController.delegate = self

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

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

委托方法

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

 let videoURL = info["UIImagePickerControllerReferenceURL"] as? NSURL
 print(videoURL!)
 imagePickerController.dismiss(animated: true, completion: nil)
}
于 2018-10-29T05:24:36.727 回答
1

试试我做的这个豆荚:

https://github.com/jhonyourangel/ImagePickerWhatsApp

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

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

先决条件

为了使用 ImageVideoPicker,您需要 cocoapods 和已经创建的 xCode 项目

安装

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

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

pod 'ImagePickerWhatsApp'

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

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

如何使用它

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

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

代表

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

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

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

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

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

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
        }
    }
}

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

图像和视频作为数据

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

为了从资产 ImageVideoPicker 中获取数据,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)
    }
}

一切都会很有趣

于 2018-06-13T06:48:52.287 回答
0

针对当前版本的 Swift 更新:

// Check if the asset is of video media type.
guard (asset.mediaType == PHAssetMediaType.video)   else {
    print("Not a valid video media type")
    return
}

// Obtain the URL of the video.
PHCachingImageManager().requestAVAsset(forVideo: asset, options: nil, resultHandler: {(asset: AVAsset?, audioMix: AVAudioMix?, info: [AnyHashable : Any]?) in
    let asset = asset as! AVURLAsset
    print("asset.url: ", asset.url) // Here is video URL
    // Play the video.
    DispatchQueue.main.async(execute: {

        let player = AVPlayer(url: asset.url)
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        self.present(playerViewController, animated: true) {
            playerViewController.player!.play()
        }
    })
})
于 2017-10-20T04:42:04.947 回答
0
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
}
于 2016-02-29T01:33:52.143 回答
-1
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)
}

委托方法

func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) {
  self.dismissViewControllerAnimated(true, completion: nil)
  imageView.image = image
}
于 2015-06-08T19:22:06.510 回答