如何让UIImagePickerController仅显示iOS系统的Videos文件夹?
解决方案:仅显示系统Videos相册的视频内容
嘿,这个问题我之前帮不少开发者处理过——UIImagePickerController确实没有直接的API让你指定只显示系统的Videos相册,但咱们有两种适配不同iOS版本的可行方案,完美匹配你的需求:
方案1:iOS 14+ 推荐使用 PHImagePickerController
从iOS14开始,苹果推出了更灵活的PHImagePickerController,它支持直接指定偏好的相册,代码实现非常简洁:
import PhotosUI // 1. 配置选择器参数 var pickerConfig = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared()) pickerConfig.filter = .videos // 仅筛选视频类型 pickerConfig.selectionLimit = 1 // 根据需求设置选择数量,0表示无限制 // 2. 获取系统的Videos智能相册 if let videosAlbum = PHAssetCollection.fetchAssetCollections( with: .smartAlbum, subtype: .smartAlbumVideos, options: nil ).firstObject { pickerConfig.preferredAssetCollection = videosAlbum // 指定默认显示该相册 } // 3. 初始化并弹出选择器 let picker = PHPickerViewController(configuration: pickerConfig) picker.delegate = self present(picker, animated: true, completion: nil)
注意事项:
- 记得实现
PHPickerViewControllerDelegate协议来处理用户选择的视频结果 - Info.plist中必须添加
NSPhotoLibraryUsageDescription权限描述,iOS14+如果需要保存视频还要添加NSPhotoLibraryAddUsageDescription
方案2:iOS 10-13 自定义视频选择界面
由于UIImagePickerController在iOS13及以下不支持指定相册,我们需要自己构建选择界面,直接从系统Videos相册获取视频资源:
步骤1:获取系统Videos相册
import Photos func fetchSystemVideosAlbum() -> PHAssetCollection? { // 通过智能相册类型和子类型精准定位系统Videos相册,不受语言本地化影响 let albumFetchResult = PHAssetCollection.fetchAssetCollections( with: .smartAlbum, subtype: .smartAlbumVideos, options: nil ) return albumFetchResult.firstObject }
步骤2:获取相册内的所有视频资源
func fetchVideosInAlbum(_ album: PHAssetCollection) -> PHFetchResult<PHAsset> { let fetchOptions = PHFetchOptions() // 按创建时间倒序排列 fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] // 仅筛选视频类型 fetchOptions.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.video.rawValue) return PHAsset.fetchAssets(in: album, options: fetchOptions) }
步骤3:自定义UI展示视频
你可以用UITableView或UICollectionView来展示视频列表,通过PHImageManager获取视频缩略图:
let imageManager = PHImageManager.default() let videoAssets = fetchVideosInAlbum(yourVideosAlbum) videoAssets.enumerateObjects { asset, index, stop in let thumbnailOptions = PHImageRequestOptions() thumbnailOptions.isSynchronous = false // 请求视频缩略图 imageManager.requestImage( for: asset, targetSize: CGSize(width: 150, height: 150), contentMode: .aspectFill, options: thumbnailOptions ) { thumbnailImage, info in // 更新你的列表UI } }
额外处理:视频预览与导出
用户点击视频后,你可以用AVPlayerViewController做预览,或者通过PHImageManager导出视频原文件,满足业务需求。
关键提醒
- 无论哪种方案,都要先申请相册访问权限,调用
PHPhotoLibrary.requestAuthorization获取用户授权 - 系统Videos相册的
subtype是.smartAlbumVideos,不要用标题匹配,避免本地化问题
内容的提问来源于stack exchange,提问作者Raptor
相关产品推荐
相关产品推荐

