Search code examples
iosswiftavplayerphassetphotokit

Access video using localIdentifier, swift


I want to open a video, for which I have the localIdentifier. I know I can create an AVPlayer like this,

let player = AVPlayer(URL: NSURL(fileURLWithPath: path))

Is it possible to open a video by providing its localIdentifier?

I am using the video as a PHAsset to obtain its localIdentifier. It is possible to use PHFetchOptions and fetchAssetCollectionsWithLocalIdentifiers, however, it would be like a query. Is there a more direct way to access a video or an image if I have its localIdentifier?


Solution

  • If you're going to present a video asset in an AVPlayer, the best thing to request from Photos for providing to the player is an AVPlayerItem. Supposing you have the localIdentifier for a video asset in the Photos library, you'll need to first find the PHAsset representing that asset:

    let assets = PHAsset.fetchAssetsWithLocalIdentifiers([identifier], options: nil)
    guard let asset = assets.firstObject as? PHAsset
        else { fatalError("no asset") }
    

    Once you have a PHAsset you can use PHImageManager to fetch the asset's video content (in the form of an AVPlayerItem):

    let options = PHVideoRequestOptions()
    options.networkAccessAllowed = true
    let requestID = PHImageManager.defaultManager().requestPlayerItemForVideo(asset, 
        options: options, 
        resultHandler: { playerItem, info in
            guard let item = playerItem
                else { fatalError("can't get player item: \(info)") }
    
            // send the item to whatever you're playing AV content with, e.g.
            myAVPlayerViewController.player = AVPlayer(playerItem: item)
        }
    )