使用iOS中的Photos Framework将视频保存到自定义相册

时间:2017-06-21 07:14:00

标签: ios swift ios9 photosframework

我想使用NewAlbum将使用自定义相机拍摄的视频保存到Photos Library中的Photos Framework专用相册中。 我找到了一些答案,但他们提到了ALAssetsLibrary的使用,现在已弃用。

如果您需要更多详细信息,请告诉我,如果我错过了某些内容,请纠正我。 感谢

1 个答案:

答案 0 :(得分:4)

我找到了create a PHAsset from an Video的解决方案:

代码区块1:

PhotoLibrary.shared().performChanges({
    let createAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(/*Your url here*/)
    placeholder = createAssetRequest.placeholderForCreatedAsset
    identifier = placeholder.localIdentifier
}, completionHandler: {
    success, error in 
    /* 
       Fetch Asset with the identifier here
       after that, add the PHAsset into an album
    */
    newAsset = PHAsset.fetchAssets(withLocalIdentifiers: [identifier], options: nil).firstObject
}

您可以使用以下代码段添加PHAsset

代码区块2:

// Consider we have a known localIdentifier for a specific PHAssetCollection defined as -> let collectionIdentifier: String
guard let collection: PHAssetCollection = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [collectionIdentifier], options: nil).fistObject else {
   // handle Error
   return
}
PhotoLibrary.shared().performChanges({

    guard let addAssetRequest = PHAssetCollectionChangeRequest(for: collection) else { return }

    addAssetRequest.addAssets([newAsset] as NSArray)
}, completionHandler: {
    success, error in
    //handle error or stuff you want to do after that here
})

编辑用于创建PHAssetCollection

的示例

在这种情况下,我在PHAssetCollection闭包创建后创建了performChanges(_:,completionHandler:),并将其放在该函数的@escaping闭包中。

PHPhotoLibrary.shared().performChanges({

        let createRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: name)
        placeHolderIdentifier = createRequest.placeholderForCreatedAssetCollection.localIdentifier

    }, completionHandler: {
        success, error in
        if success {
            var createdCollection: PHAssetCollection? = nil
            if placeHolderIdentifier != nil {
                createdCollection = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [placeHolderIdentifier!], options: nil).firstObject
            }
            completion(success, createdCollection as? T)
        } else {
            LogError("\(error)")
            completion(success, nil)
        }
    })