【问题标题】:Is it possible to limit the video duration when selecting a video using `PHPickerViewController`?使用`PHPickerViewController`选择视频时是否可以限制视频时长?
【发布时间】:2021-12-28 05:46:08
【问题描述】:

我尝试使用 PHPickerViewController 选择资产来替代我的 UIImagePickerController,但是在设置 filterconfig 选项时,我没有看到设置返回视频长度限制的方法.即使用UIImagePickerControllervideoMaximumDuration 的方式。

有没有人找到任何锻炼方式?

private func presentPicker(filter: PHPickerFilter?)-> PHPickerViewController {
    var configuration = PHPickerConfiguration(photoLibrary: .shared())
    
    // Set the filter type according to the user’s selection.
    configuration.filter = filter
    // Set the mode to avoid transcoding, if possible, if your app supports arbitrary image/video encodings.
    configuration.preferredAssetRepresentationMode = .current
    // Set the selection behavior to respect the user’s selection order.
    configuration.selection = .ordered
    // Set the selection limit to enable singular selection.
    configuration.selectionLimit = 1
    // Set the preselected asset identifiers with the identifiers that the app tracks.
    configuration.preselectedAssetIdentifiers = []
    
    let picker = PHPickerViewController(configuration: configuration)
    //picker.delegate = self
    //present(picker, animated: true)
    return picker
}

【问题讨论】:

  • 我认为你不能用 PHPickerViewController 设置限制。

标签: ios swift photo photosui


【解决方案1】:

查看PHPickerFilterPHPickerViewController 的文档,我看不到任何按视频长度过滤的本地方法。

我能想到的最好的解决方案是符合委托PHPickerViewControllerDelegate并在用户选择后检查视频长度。

您尚未提供其余代码,但您应该遵守PHPickerViewControllerDelegate 并实现所需的方法:

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
      func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
       guard let provider = results.first?.itemProvider else { return }
       provider.loadItem(forTypeIdentifier: UTType.movie.identifier, options: [:]) { (videoURL, error) in
           // Check the video length here
       }
   }
}

有关如何加载视频的示例,请参见上面的代码。从这里您可以按照一些现有的答案来了解如何提取视频时长。如果视频时长在您想要过滤的范围内,请使用FileManager 将其复制到适当的位置,然后按照您认为合适的方式处理它,如果它不适合(IE 太长,或者太短,你不喜欢),然后丢弃它并使用警报/消息告诉用户。

以下是有关如何获取视频时长的示例。注意:您只需要将对 url 的引用替换为您在完成处理程序中可以访问的 videoURL(请参阅注释)。

Get the accurate duration of a video

另一种解决方案是使用来自第三方的更强大的照片选择器。

这有一个缺点,即要求用户为其整个照片库提供权限(因为照片选择器不需要提示权限,因为它是 iOS 提供的沙盒视图控制器)。它还会在您的应用中引入另一个依赖项。

如果这些缺点适合您的用例,那么这可能正是您正在寻找的。​​p>

这是一个提供更强大过滤器的库:https://github.com/Yummypets/YPImagePicker

请参阅自述文件中的“视频”部分。它允许您指定最小和最大视频持续时间。

【讨论】:

    猜你喜欢
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 2010-09-25
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    相关资源
    最近更新 更多