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