iPhone-如何创建自定义相册,并以编程方式为相机卷中的照片指定自定义名称?
我正在开发一个iPhone照片应用程序,因此我需要在camera roll中创建一个名为“My album”的单独相册,并需要在新创建的目录中使用自定义名称保存我的UIImageView图像,例如“My image.png”iPhone-如何创建自定义相册,并以编程方式为相机卷中的照片指定自定义名称?,iphone,ios,camera,nsfilemanager,Iphone,Ios,Camera,Nsfilemanager,我正在开发一个iPhone照片应用程序,因此我需要在camera roll中创建一个名为“My album”的单独相册,并需要在新创建的目录中使用自定义名称保存我的UIImageView图像,例如“My image.png” 如何实现这一点?您可以在iOS中使用以下代码行轻松创建自定义相册并添加图像: // Create the new album. __block PHObjectPlaceholder *myAlbum; [[PHPhotoLibrary sharedPhotoLibrary
如何实现这一点?您可以在iOS中使用以下代码行轻松创建自定义相册并添加图像:
// Create the new album.
__block PHObjectPlaceholder *myAlbum;
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetCollectionChangeRequest *changeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
myAlbum = changeRequest.placeholderForCreatedAssetCollection;
} completionHandler:^(BOOL success, NSError *error) {
if (success) {
PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[myAlbum.localIdentifier] options:nil];
PHAssetCollection *assetCollection = fetchResult.firstObject;
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
// add asset
PHAssetCollectionChangeRequest *assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
[assetCollectionChangeRequest addAssets:@[[assetChangeRequest placeholderForCreatedAsset]]];
} completionHandler:^(BOOL success, NSError *error) {
if (!success) {
NSLog(@"Error: %@", error);
}
}];
} else {
NSLog(@"Error: %@", error);
}
}];
使用iOS中的以下代码行,您可以轻松创建自定义相册并添加图像:
// Create the new album.
__block PHObjectPlaceholder *myAlbum;
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetCollectionChangeRequest *changeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
myAlbum = changeRequest.placeholderForCreatedAssetCollection;
} completionHandler:^(BOOL success, NSError *error) {
if (success) {
PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[myAlbum.localIdentifier] options:nil];
PHAssetCollection *assetCollection = fetchResult.firstObject;
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
// add asset
PHAssetCollectionChangeRequest *assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
[assetCollectionChangeRequest addAssets:@[[assetChangeRequest placeholderForCreatedAsset]]];
} completionHandler:^(BOOL success, NSError *error) {
if (!success) {
NSLog(@"Error: %@", error);
}
}];
} else {
NSLog(@"Error: %@", error);
}
}];
它从iOS 5.0开始工作。
请导入AssetLibrary/AssetLibrary.h
ALAssetsLibrary* libraryFolder = [[ALAssetsLibrary alloc] init];
[libraryFolder addAssetsGroupAlbumWithName:@"My Album" resultBlock:^(ALAssetsGroup *group)
{
NSLog(@"Adding Folder:'My Album', success: %s", group.editable ? "Success" : "Already created: Not Success");
} failureBlock:^(NSError *error)
{
NSLog(@"Error: Adding on Folder");
}];
它从iOS 5.0开始工作。
请导入AssetLibrary/AssetLibrary.h
ALAssetsLibrary* libraryFolder = [[ALAssetsLibrary alloc] init];
[libraryFolder addAssetsGroupAlbumWithName:@"My Album" resultBlock:^(ALAssetsGroup *group)
{
NSLog(@"Adding Folder:'My Album', success: %s", group.editable ? "Success" : "Already created: Not Success");
} failureBlock:^(NSError *error)
{
NSLog(@"Error: Adding on Folder");
}];
您可以尝试以下方法为iOS 7和iOS 8创建相册
#define PHOTO_ALBUM_NAME @"AlbumName Videos"
-(void)createAlbum{
// PHPhotoLibrary_class will only be non-nil on iOS 8.x.x
Class PHPhotoLibrary_class = NSClassFromString(@"PHPhotoLibrary");
if (PHPhotoLibrary_class) {
// iOS 8..x. . code that has to be called dynamically at runtime and will not link on iOS 7.x.x ...
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:PHOTO_ALBUM_NAME];
} completionHandler:^(BOOL success, NSError *error) {
if (!success) {
NSLog(@"Error creating album: %@", error);
}else{
NSLog(@"Created");
}
}];
}else{
[self.library addAssetsGroupAlbumWithName:PHOTO_ALBUM_NAME resultBlock:^(ALAssetsGroup *group) {
NSLog(@"adding album:'Compressed Videos', success: %s", group.editable ? "YES" : "NO");
if (group.editable == NO) {
}
} failureBlock:^(NSError *error) {
NSLog(@"error adding album");
}];
}}
您可以尝试以下方法为iOS 7和iOS 8创建相册
#define PHOTO_ALBUM_NAME @"AlbumName Videos"
-(void)createAlbum{
// PHPhotoLibrary_class will only be non-nil on iOS 8.x.x
Class PHPhotoLibrary_class = NSClassFromString(@"PHPhotoLibrary");
if (PHPhotoLibrary_class) {
// iOS 8..x. . code that has to be called dynamically at runtime and will not link on iOS 7.x.x ...
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:PHOTO_ALBUM_NAME];
} completionHandler:^(BOOL success, NSError *error) {
if (!success) {
NSLog(@"Error creating album: %@", error);
}else{
NSLog(@"Created");
}
}];
}else{
[self.library addAssetsGroupAlbumWithName:PHOTO_ALBUM_NAME resultBlock:^(ALAssetsGroup *group) {
NSLog(@"adding album:'Compressed Videos', success: %s", group.editable ? "YES" : "NO");
if (group.editable == NO) {
}
} failureBlock:^(NSError *error) {
NSLog(@"error adding album");
}];
}}
由于
资产库
已弃用,请改用照片
框架(iOS 8及更高版本)
您可以使用共享的PHPhotoLibrary
对象来创建新照片,但不能给它们指定名称,因为您将使用需要由photos.app管理的资产。每个资产都有特定的属性。您可以获取对象、请求更改、资产/缩略图加载和缓存等
要创建自定义相册,请使用
简要示例:
// Swift 3.0
func createPhotoLibraryAlbum(name: String) {
var albumPlaceholder: PHObjectPlaceholder?
PHPhotoLibrary.shared().performChanges({
// Request creating an album with parameter name
let createAlbumRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: name)
// Get a placeholder for the new album
albumPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
}, completionHandler: { success, error in
if success {
guard let placeholder = albumPlaceholder else {
fatalError("Album placeholder is nil")
}
let fetchResult = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [placeholder.localIdentifier], options: nil)
guard let album: PHAssetCollection = fetchResult.firstObject else {
// FetchResult has no PHAssetCollection
return
}
// Saved successfully!
print(album.assetCollectionType)
}
else if let e = error {
// Save album failed with error
}
else {
// Save album failed with no error
}
})
}
不要忘记导入照片库
要在该相册上创建新的照片资源,请使用
更新:
我们需要请求访问才能使用照片库:
PHPhotoLibrary.requestAuthorization { status in
switch status {
...
}
从iOS 10及更高版本开始,我们还需要在target.plist文件中为“隐私-照片库使用说明”添加访问条目:
NSPhotoLibraryUsageDescription
需要访问照片才能提供应用程序功能
由于资产库
已弃用,请改用照片
框架(iOS 8及更高版本)
您可以使用共享的PHPhotoLibrary
对象来创建新照片,但不能给它们指定名称,因为您将使用需要由photos.app管理的资产。每个资产都有特定的属性。您可以获取对象、请求更改、资产/缩略图加载和缓存等
要创建自定义相册,请使用
简要示例:
// Swift 3.0
func createPhotoLibraryAlbum(name: String) {
var albumPlaceholder: PHObjectPlaceholder?
PHPhotoLibrary.shared().performChanges({
// Request creating an album with parameter name
let createAlbumRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: name)
// Get a placeholder for the new album
albumPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
}, completionHandler: { success, error in
if success {
guard let placeholder = albumPlaceholder else {
fatalError("Album placeholder is nil")
}
let fetchResult = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [placeholder.localIdentifier], options: nil)
guard let album: PHAssetCollection = fetchResult.firstObject else {
// FetchResult has no PHAssetCollection
return
}
// Saved successfully!
print(album.assetCollectionType)
}
else if let e = error {
// Save album failed with error
}
else {
// Save album failed with no error
}
})
}
不要忘记导入照片库
要在该相册上创建新的照片资源,请使用
更新:
我们需要请求访问才能使用照片库:
PHPhotoLibrary.requestAuthorization { status in
switch status {
...
}
从iOS 10及更高版本开始,我们还需要在target.plist文件中为“隐私-照片库使用说明”添加访问条目:
NSPhotoLibraryUsageDescription
需要访问照片才能提供应用程序功能
创建新相册:
/// Create album with given title
/// - Parameters:
/// - title: the title
/// - completionHandler: the completion handler
func createAlbum(withTitle title: String, completionHandler: @escaping (PHAssetCollection?) -> ()) {
DispatchQueue.global(qos: .background).async {
var placeholder: PHObjectPlaceholder?
PHPhotoLibrary.shared().performChanges({
let createAlbumRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: title)
placeholder = createAlbumRequest.placeholderForCreatedAssetCollection
}, completionHandler: { (created, error) in
var album: PHAssetCollection?
if created {
let collectionFetchResult = placeholder.map { PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [$0.localIdentifier], options: nil) }
album = collectionFetchResult?.firstObject
}
completionHandler(album)
})
}
}
获取具有指定名称的相册:
/// Get album with given title
/// - Parameters:
/// - title: the title
/// - completionHandler: the completion handler
func getAlbum(title: String, completionHandler: @escaping (PHAssetCollection?) -> ()) {
DispatchQueue.global(qos: .background).async { [weak self] in
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", title)
let collections = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
if let album = collections.firstObject {
completionHandler(album)
} else {
self?.createAlbum(withTitle: title, completionHandler: { (album) in
completionHandler(album)
})
}
}
}
并将照片保存到相册:
func save(photo: UIImage, toAlbum titled: String, completionHandler: @escaping (Bool, Error?) -> ()) {
getAlbum(title: titled) { (album) in
DispatchQueue.global(qos: .background).async {
PHPhotoLibrary.shared().performChanges({
let assetRequest = PHAssetChangeRequest.creationRequestForAsset(from: photo)
let assets = assetRequest.placeholderForCreatedAsset
.map { [$0] as NSArray } ?? NSArray()
let albumChangeRequest = album.flatMap { PHAssetCollectionChangeRequest(for: $0) }
albumChangeRequest?.addAssets(assets)
}, completionHandler: { (success, error) in
completionHandler(success, error)
})
}
}
}
创建新相册:
/// Create album with given title
/// - Parameters:
/// - title: the title
/// - completionHandler: the completion handler
func createAlbum(withTitle title: String, completionHandler: @escaping (PHAssetCollection?) -> ()) {
DispatchQueue.global(qos: .background).async {
var placeholder: PHObjectPlaceholder?
PHPhotoLibrary.shared().performChanges({
let createAlbumRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: title)
placeholder = createAlbumRequest.placeholderForCreatedAssetCollection
}, completionHandler: { (created, error) in
var album: PHAssetCollection?
if created {
let collectionFetchResult = placeholder.map { PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [$0.localIdentifier], options: nil) }
album = collectionFetchResult?.firstObject
}
completionHandler(album)
})
}
}
获取具有指定名称的相册:
/// Get album with given title
/// - Parameters:
/// - title: the title
/// - completionHandler: the completion handler
func getAlbum(title: String, completionHandler: @escaping (PHAssetCollection?) -> ()) {
DispatchQueue.global(qos: .background).async { [weak self] in
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", title)
let collections = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
if let album = collections.firstObject {
completionHandler(album)
} else {
self?.createAlbum(withTitle: title, completionHandler: { (album) in
completionHandler(album)
})
}
}
}
并将照片保存到相册:
func save(photo: UIImage, toAlbum titled: String, completionHandler: @escaping (Bool, Error?) -> ()) {
getAlbum(title: titled) { (album) in
DispatchQueue.global(qos: .background).async {
PHPhotoLibrary.shared().performChanges({
let assetRequest = PHAssetChangeRequest.creationRequestForAsset(from: photo)
let assets = assetRequest.placeholderForCreatedAsset
.map { [$0] as NSArray } ?? NSArray()
let albumChangeRequest = album.flatMap { PHAssetCollectionChangeRequest(for: $0) }
albumChangeRequest?.addAssets(assets)
}, completionHandler: { (success, error) in
completionHandler(success, error)
})
}
}
}
///保存图像或视频(保存图片或视频)(kUTTypeImage、kUTTypeMovie)
///如果指定了唱片集名称,则添加到唱片集,如果需要,则创建唱片集
///@params mediaArray UIImage,图像或视频的文件URL
+(void)_saveMediaArray:(NSArray*)mediaArray
选项:(LAImageSaverOptions*)选项
完成:(无效(^)(n错误*_可为空错误))完成
{
NSInteger uu块计数=0;
[PHPhotoLibrary.sharedPhotoLibrary性能更改:^{
//如果需要,创建相册
PhaseSetCollectionChangeRequest*assetCollectionChangeRequest=nil;
NSMutableArray*assetChangeRequestPlaceholders=nil;
如果(options.targetAlbumName.length>0){
assetChangeRequestPlaceholders=[NSMutableArray阵列容量:mediaArray.count];
PHFetchOptions*fetchOptions=PHFetchOptions.new;
//fetchOptions.includeAssetSourceTypes=PHAssetSourceTypeUserLibrary;
fetchOptions.predicate=[NSPredicate predicateWithFormat:@“localizedTitle=%@”,options.targetAlbumName];//不能用 块形式的 谓语
PHAssetCollection*assetCollection=[PHAssetCollection获取AssetCollectionSwithType:PHAssetCollectionTypeAlbum子类型:PhasSetCollectionSubtypeAlbum常规选项:获取选项].firstObject;
if(nil==assetCollection){
assetCollectionChangeRequest=[PhaseSetCollectionChangeRequestCreationRequestforAssetCollectionWithTitle:options.targetAlbumName];
}否则{
assetCollectionChangeRequest=[PhaseSetCollectionChangeRequestChangeRequestForAssetCollection:assetCollection];
}
}
//保存图像
for(mediaArray中的id项){
PhaseSetChangeRequest*assetChangeRequest=nil;
//图像对象
if([item iskindof类:UIImage.class]){
UIImage*图像=(UIImage*)项;
assetChangeRequest=[PhaseSetChangeRequest creationRequestForAssetFromImage:image];
[assetChangeRequestPlaceholders addObject:assetChangeRequest.placeholderForCreatedAsset];
++计数;
继续;
}
//图像或电影的文件url
NSURL*文件URL=(NSURL*)项;
if([item iskindof类:NSURL.class]&&fileURL.isFileURL){
NSString*extension=fileURL.pathExtension;
if(extension.length==0){
NSLog(@“非法文件URL(无路径扩展):%@”,文件URL);
continue;//文件url非法
}
CFStringRef uti=UTTypeCreatePreferredIden