简体   繁体   中英

Save video to a custom Album using Photos Framework in iOS

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM