Search code examples
iosswiftuiimagepickercontrollergalleryuiimagepickercontrollermediatype

Get Video or Video Info Without open Gallery Swift


I am trying to get Video without open Gallery or UIImagePickerControllerlike I got success in getting images without open gallery. Is there any way to get files without open UIImagePickerController.

Can someone please explain to me how to get files without open UIImagePickerController. Any help would be greatly appreciated.

Thanks in advance.


Solution

  • For example, using the following code, you can get the latest user video:

    import Photos
    
    let options = PHFetchOptions()
    options.fetchLimit = 1
    let sortDescriptor = NSSortDescriptor(key: "creationDate", ascending: false)
    options.sortDescriptors = [sortDescriptor]
    let fetchResult = PHAsset.fetchAssets(with: .video, options: options)
    if fetchResult.count == 0 {
        // user has no video...
        return
    }
    let asset = fetchResult[0]
    let requestOptions = PHVideoRequestOptions()
    let manager = PHImageManager.default()
    

    Then, if you want to get the video itself, use the following code:

    manager.requestAVAsset(forVideo: asset, options: requestOptions, resultHandler: { oAsset, oAudioMix, oDict in
        if let urlAsset = oAsset as? AVURLAsset {
            let url = urlAsset.url
            // use URL to get file content
        }
    })
    

    Otherwise, if you just want to play the video, use the following code:

    manager.requestPlayerItem(forVideo: asset, options: requestOptions, resultHandler: { oPlayerItem, oDict in
        // do something with oPlayerItem
    })
    

    For more information you can read this