Save Video to a Custom Album Using Photos Framework in iOS

Save Video into Custom Album iOS

You can use this link to save the video..
GitHub Link

Import this two files into your project.

  1. ALAssetsLibrary+CustomPhotoAlbum.h
  2. ALAssetsLibrary+CustomPhotoAlbum.m

Then in your save IBAction method write this lines..

if(UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(outputFilePath)){

NSURL *muyrl=[NSURL fileURLWithPath:outputFilePath];
[library saveVideo:muyrl toAlbum:albumName withCompletionBlock:^(NSError *error)
{
if (error!=nil) {
NSLog(@"Big error: %@", [error description]);
}
}];

Where.. outputfilepath is your videopath and if you have url then save it with URL name.
library is ALAssetLibrary that define in .h file
albumName is your Album name what do you want..I hope this will help you.

How to save image to custom album?

I came up with this singleton class to handle it:

import Photos

class CustomPhotoAlbum {

static let albumName = "Flashpod"
static let sharedInstance = CustomPhotoAlbum()

var assetCollection: PHAssetCollection!

init() {

func fetchAssetCollectionForAlbum() -> PHAssetCollection! {

let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", CustomPhotoAlbum.albumName)
let collection = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)

if let firstObject: AnyObject = collection.firstObject {
return collection.firstObject as! PHAssetCollection
}

return nil
}

if let assetCollection = fetchAssetCollectionForAlbum() {
self.assetCollection = assetCollection
return
}

PHPhotoLibrary.sharedPhotoLibrary().performChanges({
PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(CustomPhotoAlbum.albumName)
}) { success, _ in
if success {
self.assetCollection = fetchAssetCollectionForAlbum()
}
}
}

func saveImage(image: UIImage) {

if assetCollection == nil {
return // If there was an error upstream, skip the save.
}

PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
let assetPlaceholder = assetChangeRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection)
albumChangeRequest.addAssets([assetPlaceholder])
}, completionHandler: nil)
}

}

When you first instantiate the class, the custom album will be created if it doesn't already exist. You can save an image like this:

CustomPhotoAlbum.sharedInstance.saveImage(image)

NOTE: The CustomPhotoAlbum class assumes the app already has permission to access the Photo Library. Dealing with the permissions is a bit outside the scope of this question/answer. So make sure PHPhotoLibrary.authorizationStatus() == .Authorize before you use it. And request authorization if necessary.

Save images with phimagemanager to custom album?

This is how I do:

At the top:

import Photos

var image: UIImage!
var assetCollection: PHAssetCollection!
var albumFound : Bool = false
var photosAsset: PHFetchResult!
var assetThumbnailSize:CGSize!
var collection: PHAssetCollection!
var assetCollectionPlaceholder: PHObjectPlaceholder!

Creating the album:

func createAlbum() {
//Get PHFetch Options
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", "camcam")
let collection : PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)
//Check return value - If found, then get the first album out
if let _: AnyObject = collection.firstObject {
self.albumFound = true
assetCollection = collection.firstObject as! PHAssetCollection
} else {
//If not found - Then create a new album
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let createAlbumRequest : PHAssetCollectionChangeRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle("camcam")
self.assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
}, completionHandler: { success, error in
self.albumFound = success

if (success) {
let collectionFetchResult = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([self.assetCollectionPlaceholder.localIdentifier], options: nil)
print(collectionFetchResult)
self.assetCollection = collectionFetchResult.firstObject as! PHAssetCollection
}
})
}
}

When saving the photo:

func saveImage(){
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(self.image)
let assetPlaceholder = assetRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection, assets: self.photosAsset)
albumChangeRequest!.addAssets([assetPlaceholder!])
}, completionHandler: { success, error in
print("added image to album")
print(error)

self.showImages()
})
}

Showing the images from that album:

func showImages() {
//This will fetch all the assets in the collection

let assets : PHFetchResult = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: nil)
print(assets)

let imageManager = PHCachingImageManager()
//Enumerating objects to get a chached image - This is to save loading time
assets.enumerateObjectsUsingBlock{(object: AnyObject!,
count: Int,
stop: UnsafeMutablePointer<ObjCBool>) in

if object is PHAsset {
let asset = object as! PHAsset
print(asset)

let imageSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight)

let options = PHImageRequestOptions()
options.deliveryMode = .FastFormat

imageManager.requestImageForAsset(asset, targetSize: imageSize, contentMode: .AspectFill, options: options, resultHandler: {(image: UIImage?,
info: [NSObject : AnyObject]?) in
print(info)
print(image)
})
}
}

Save video to the gallery and get the path for the video stored to Gallery

This worked for me perfectly.

Swift 3.1 ->

PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url!)
}) { saved, error in
if saved {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]

// After uploading we fetch the PHAsset for most recent video and then get its current location url

let fetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions).lastObject
PHImageManager().requestAVAsset(forVideo: fetchResult!, options: nil, resultHandler: { (avurlAsset, audioMix, dict) in
let newObj = avurlAsset as! AVURLAsset
print(newObj.url)
// This is the URL we need now to access the video from gallery directly.
})
}
}


Related Topics



Leave a reply



Submit