使用localIdentifier访问视频,swift

时间:2016-01-15 17:11:09

标签: ios swift avplayer phasset photokit

我想打开一个视频,我有localIdentifier。我知道我可以像这样创建一个AVPlayer,

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

是否可以通过提供localIdentifier来打开视频?

我将视频用作PHAsset以获取其localIdentifier。可以使用PHFetchOptions和fetchAssetCollectionsWithLocalIdentifiers,但是,它就像一个查询。如果我有localIdentifier,是否有更直接的方式来访问视频或图像?

1 个答案:

答案 0 :(得分:2)

如果您要在AVPlayer中展示视频资源,请向照片提供给玩家的最佳选择是AVPlayerItem。假设您在照片库中拥有视频资产localIdentifier,则需要先找到代表该资产的PHAsset

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

获得PHAsset后,您可以使用PHImageManager获取资源的视频内容(以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)
    }
)