vez varias todas seleccionar para organizar mac las fotos descargar cómo compartido como album ios swift uiimage ios8 phasset

ios - varias - ¿Guardar imágenes con phimagemanager en un álbum personalizado?



icloud para windows (5)

Estoy creando una aplicación que toma imágenes con AVFoundation y quiero guardarlas en un álbum personalizado que luego puedo consultar y mostrar en mi aplicación. (Preferiría no tenerlos en el rollo general de fotos, a menos que el usuario lo quiera). Realmente no puedo encontrar nada que muestre cómo hacerlo en Swift ... o en absoluto. ¿Hay alguna otra manera en que se supone que debo hacer esto?

Encontré este ejemplo en SO, pero no tiene sentido para mí y no puedo hacerlo funcionar.

func savePhoto() { var albumFound : Bool = false var assetCollection: PHAssetCollection! var photosAsset: PHFetchResult! var assetThumbnailSize:CGSize! // Create the album if does not exist (in viewDidLoad) if let first_Obj:AnyObject = collection.firstObject{ //found the album self.albumFound = true self.assetCollection = collection.firstObject as PHAssetCollection }else{ //Album placeholder for the asset collection, used to reference collection in completion handler var albumPlaceholder:PHObjectPlaceholder! //create the folder NSLog("/nFolder /"%@/" does not exist/nCreating now...", albumName) PHPhotoLibrary.sharedPhotoLibrary().performChanges({ let request = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(albumName) albumPlaceholder = request.placeholderForCreatedAssetCollection }, completionHandler: {(success:Bool, error:NSError!)in NSLog("Creation of folder -> %@", (success ? "Success":"Error!")) self.albumFound = (success ? true:false) if(success){ let collection = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([albumPlaceholder.localIdentifier], options: nil) self.assetCollection = collection?.firstObject as PHAssetCollection } }) } let bundle = NSBundle.mainBundle() let myFilePath = bundle.pathForResource("highlight1", ofType: "mov") let videoURL:NSURL = NSURL.fileURLWithPath(myFilePath!)! let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0), { PHPhotoLibrary.sharedPhotoLibrary().performChanges({ //let createAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage let createAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(videoURL) let assetPlaceholder = createAssetRequest.placeholderForCreatedAsset let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection, assets: self.photosAsset) albumChangeRequest.addAssets([assetPlaceholder]) }, completionHandler: {(success, error)in dispatch_async(dispatch_get_main_queue(), { NSLog("Adding Image to Library -> %@", (success ? "Sucess":"Error!")) //picker.dismissViewControllerAnimated(true, completion: nil) }) }) }) }

¡Cualquier ayuda / explicación sería genial!


Así es como lo hago:

En la cima:

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

Creando el álbum:

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

Al guardar la foto:

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

Mostrando las imágenes de ese álbum:

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


Como se actualizó para Swift 2.1+ y para Video en caso de que intente hacer eso y termine aquí. Compare las otras respuestas con ligeras diferencias (como usar imágenes en lugar de videos)

var photosAsset: PHFetchResult! var collection: PHAssetCollection! var assetCollectionPlaceholder: PHObjectPlaceholder! //Make sure we have custom album for this app if haven''t already let fetchOptions = PHFetchOptions() fetchOptions.predicate = NSPredicate(format: "title = %@", "MY_APP_ALBUM_NAME") self.collection = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions).firstObject as! PHAssetCollection //if we don''t have a special album for this app yet then make one if self.collection == nil { PHPhotoLibrary.sharedPhotoLibrary().performChanges({ let createAlbumRequest : PHAssetCollectionChangeRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle("MY_APP_ALBUM_NAME") self.assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection }, completionHandler: { success, error in if success { let collectionFetchResult = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([self.assetCollectionPlaceholder.localIdentifier], options: nil) print(collectionFetchResult) self.collection = collectionFetchResult.firstObject as! PHAssetCollection } }) } //save the video to Photos PHPhotoLibrary.sharedPhotoLibrary().performChanges({ let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(self.VIDEO_URL_FOR_VIDEO_YOU_MADE!) let assetPlaceholder = assetRequest!.placeholderForCreatedAsset self.photosAsset = PHAsset.fetchAssetsInAssetCollection(self.collection, options: nil) let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.collection, assets: self.photosAsset) albumChangeRequest!.addAssets([assetPlaceholder!]) }, completionHandler: { success, error in if success { print("added video to album") }else if error != nil{ print("handle error since couldn''t save video") } } })


Me gusta volver a utilizar el código que escribo, así que decidí crear una extensión para PHPhotoLibrary, donde es posible usarla como:

PHPhotoLibrary.saveImage(photo, albumName: "Trip") { asset in guard let asset = asset else { assert(false, "Asset is nil") return } PHPhotoLibrary.loadThumbnailFromAsset(asset) { thumbnail in print(thumbnail) } }

Aquí está el código: https://gist.github.com/ricardopereira/636ccd0a3c8a327c43d42e7cbca4d041


Mejoré el código de @ricardopereira y @ColossalChris. Se agregó video a la extensión y se agregó otra extensión sobre PHAsset para eliminar los errores de compilación. Funciona en veloz 2.1. Uso de muestra:

#import "Yourtargetname-Swift.h"//important! NSURL *videoURL = [[NSURL alloc] initFileURLWithPath:PATH_TO_VIDEO]; [PHPhotoLibrary saveVideo:videoURL albumName:@"my album" completion:^(PHAsset * asset) { NSLog(@"success"); NSLog(@"asset%lu",(unsigned long)asset.pixelWidth); }];

Importe ambos archivos rápidos: github.com/kv2/PHPhotoLibrary-PhotoAsset.swift

Se puede usar en Object-c siempre que importe el encabezado rápido para su destino (consulte el archivo ViewController.m ).


Responda en Objective-C y limpie un poco.

__block PHFetchResult *photosAsset; __block PHAssetCollection *collection; __block PHObjectPlaceholder *placeholder; // Find the album PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init]; fetchOptions.predicate = [NSPredicate predicateWithFormat:@"title = %@", @"YOUR_ALBUM_TITLE"]; collection = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:fetchOptions].firstObject; // Create the album if (!collection) { [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ PHAssetCollectionChangeRequest *createAlbum = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:@"YOUR_ALBUM_TITLE"]; placeholder = [createAlbum placeholderForCreatedAssetCollection]; } completionHandler:^(BOOL success, NSError *error) { if (success) { PHFetchResult *collectionFetchResult = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[placeholder.localIdentifier] options:nil]; collection = collectionFetchResult.firstObject; } }]; } // Save to the album [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ PHAssetChangeRequest *assetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:[UIImage imageWithData:imageData]]; placeholder = [assetRequest placeholderForCreatedAsset]; photosAsset = [PHAsset fetchAssetsInAssetCollection:collection options:nil]; PHAssetCollectionChangeRequest *albumChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection assets:photosAsset]; [albumChangeRequest addAssets:@[placeholder]]; } completionHandler:^(BOOL success, NSError *error) { if (success) { NSString *UUID = [placeholder.localIdentifier substringToIndex:36]; self.photo.assetURL = [NSString stringWithFormat:@"assets-library://asset/asset.PNG?id=%@&ext=JPG", UUID]; [self savePhoto]; } else { NSLog(@"%@", error); } }];

El bit al final con el UUID fue algo que encontré en otro hilo de para crear un reemplazo para la propiedad AssetURL de un ALAsset.

Nota: Vea el comentario de Chris a continuación para una respuesta más completa.