I'm trying to get all videos that are in the camera roll on a user's phone when they try and upload a video, but I'm not sure how to.
I've done this to get all pictures and noticed that if I change the .image to .video it gets all the videos, but they are still presented as an image and you can't play the video:
func fetchImagesFromDeviceLibary() {
let allPhotos = PHAsset.fetchAssets(with: .image, options: getAssetFetchOptions())
DispatchQueue.global(qos: .background).async {
//Enumerate objects
allPhotos.enumerateObjects({ (asset, count, stop) in
let imageManager = PHImageManager.default()
let targetSize = CGSize(width: 600, height: 600)
let options = PHImageRequestOptions()
options.isSynchronous = true
imageManager.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFit, options: options, resultHandler: {
(image, info) in
if let image = image {
self.videos.append(image)
self.assets.append(asset)
if self.selectedVideo == nil {
self.selectedVideo = image
}
if count == allPhotos.count - 1 {
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
})
})
}
}
func getAssetFetchOptions() -> PHFetchOptions {
let options = PHFetchOptions()
options.fetchLimit = 50
let sortDescriptor = NSSortDescriptor(key: "creationDate", ascending: false)
options.sortDescriptors = [sortDescriptor]
return options
}
How would I get all the videos and display them on screen so that you can interact with them?
After changing fetchAssets with .image to .video make the required changes in the getAssetsFetchOption().
Hope this will work for you too.
Create AVPlayer Instance :
Do not forgot to import AVKit and AVFoundation. Also try to make AvPlayer instance globally.