Created
August 7, 2019 21:33
-
-
Save Tulakshana/75f23d481b9c281ec55af501756ab47f to your computer and use it in GitHub Desktop.
Use this to save a video to an album in the phone gallery. The method creates the album if it doesn't exists.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Photos | |
class VideoHelper { | |
private static func createAlbum(name: String, completion: @escaping ((_ collection: PHAssetCollection?) -> Void)) { | |
//Get PHFetch Options | |
let fetchOptions = PHFetchOptions() | |
fetchOptions.predicate = NSPredicate(format: "title = %@", name) | |
let collection : PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions) | |
//Check return value - If found, then get the first album out | |
if let _: AnyObject = collection.firstObject { | |
completion(collection.firstObject) | |
} else { | |
//If not found - Then create a new album | |
PHPhotoLibrary.shared().performChanges({ | |
_ = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: name) | |
}, completionHandler: { success, error in | |
if (success) { | |
VideoHelper.createAlbum(name: name, completion: { (album: PHAssetCollection?) in | |
DispatchQueue.main.async { | |
completion(album) | |
} | |
}) | |
} else { | |
DispatchQueue.main.async { | |
completion(nil) | |
} | |
} | |
}) | |
} | |
} | |
static func saveCompressedVideoToPhoneGallery(url: URL, albumName: String, completion: @escaping ((_ success: Bool) -> Void)){ | |
VideoHelper.createAlbum(name: albumName) { (collection: PHAssetCollection?) in | |
guard let collection = collection else { | |
completion(false) | |
return | |
} | |
PHPhotoLibrary.shared().performChanges({ | |
let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url) | |
if let assetPlaceholder = assetRequest?.placeholderForCreatedAsset { | |
let albumChangeRequest = PHAssetCollectionChangeRequest(for: collection) | |
albumChangeRequest?.addAssets([assetPlaceholder] as NSFastEnumeration) | |
} else { | |
DispatchQueue.main.async { | |
completion(false) | |
} | |
} | |
}) { saved, error in | |
DispatchQueue.main.async { | |
completion(saved) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment