開發自定義視頻播放器時,需要讀取用戶手機相冊(非沙箱目錄)中的視頻文件,構建播放列表。iOS 系統為此提供了 ALAsset / PHAsset 框架。
自 iOS 8 起,蘋果推薦使用 Photos.framework 替代已棄用的 AssetsLibrary。以下是獲取視頻資源的標準流程:
import Photos
PHPhotoLibrary.requestAuthorization { status in
guard status == .authorized else { return }
self.fetchVideos()
}
let options = PHFetchOptions()
options.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.video.rawValue)
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
func fetchVideos() {
let assets = PHAsset.fetchAssets(with: options)
var videoList: [PHAsset] = []
assets.enumerateObjects { asset, _, _ in
videoList.append(asset)
}
// 此處可將 videoList 傳遞給播放器 UI
DispatchQueue.main.async {
self.updateUI(with: videoList)
}
}
早期版本可使用 ALAssetsLibrary 遍歷相冊,但該 API 已在 iOS 9 棄用,不建議新項目使用。
Info.plist 中添加 NSPhotoLibraryUsageDescription 說明權限用途。PHImageManager 請求 AVPlayerItem 或 AVAsset,而非直接用 URL。採用現代 Photos 框架,能獲得更好的性能、兼容性及蘋果官方長期支持。