Save video to a custom Album using Photos Framework in iOS

↘锁芯ラ 提交于 2019-11-29 23:19:07

问题


I want to save a video that is taken using a custom camera to a particular album say NewAlbum in the Photos Library using the Photos Framework. I have found some answers but they referred to use of ALAssetsLibrary which is deprecated now.

Kindly let me know if you need any more details, also rectify me if I missed something. Thanks


回答1:


I found a solution To create a PHAsset from an Video:

Code Block 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
}

you can add the PHAsset with the following snippet:

Code Block 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
})

EDIT Example for create a PHAssetCollection

In this case, I fetched the create PHAssetCollection after it was created in the performChanges(_:,completionHandler:) closure and put it in the @escaping closure of that function.

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)
        }
    })


来源:https://stackoverflow.com/questions/44669178/save-video-to-a-custom-album-using-photos-framework-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!