嗨,我现在正在开发一个基于聊天的应用程序,我想在本地保存图像,为此我使用以下代码在设备本地创建了一个目录"My_Videos"。
NSString *albumName=@"My_Videos";
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library addAssetsGroupAlbumWithName:albumName
resultBlock:^(ALAssetsGroup *group) {
NSLog(@"added album:%@", albumName);
}
failureBlock:^(NSError *error) {
NSLog(@"error adding album");
}];
它已成功创建文件夹,但现在我想从Web API下载图像并保存在我在设备中创建的" My_Videos"文件夹中。请帮帮我。
您在 AssetsLibrary 中创建新组是正确的。以下是在那里添加照片的方法:
首先,您需要将照片写入标准资源库(相机胶卷)
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:image.CGImage
orientation:(ALAssetOrientation)image.imageOrientation
completionBlock:^(NSURL* assetURL, NSError* error)
{
if (!error) {
__block BOOL albumAlredyCreated = NO;
// Check if Album already exists
[library enumerateGroupsWithTypes:ALAssetsGroupAlbum
usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if ([customAlbum compare: [group valueForProperty:ALAssetsGroupPropertyName]]==NSOrderedSame)
{
albumAlredyCreated = YES;
//Get the ALAsset instance for the saved image
[library assetForURL: assetURL
resultBlock:^(ALAsset *asset)
{
//Save photo to customAlbum
[group addAsset: asset];
} failureBlock:^(NSError *error) {
// If the user denies access to the application or if no application is allowed to access the data, the failure block will be called.
// If the data is currently unavailable, the failure block will be called.
}];
}
// Album does not exist. Create it
if (group == nil && albumAlredyCreated == NO)
{
__weak ALAssetsLibrary* weakLibrary = library;
[library addAssetsGroupAlbumWithName:customAlbum
resultBlock:^(ALAssetsGroup *group)
{
//Get the ALAsset instance for the saved image
[weakLibrary assetForURL: assetURL
resultBlock:^(ALAsset *asset) {
//Save photo to customAlbum
[group addAsset: asset];
} failureBlock:^(NSError *error) {
// If the user denies access to the application or if no application is allowed to access the data, the failure block will be called.
// If the data is currently unavailable, the failure block will be called.
}];
} failureBlock:^(NSError *error) {
// If the user denies access to the application or if no application is allowed to access the data, the failure block will be called.
}];
}
} failureBlock:^(NSError *error) {
// If the user denies access to the application, or if no application is allowed to access the data, the failureBlock is called.
}];
}
}];
虽然这可以工作,但ALAssetsLibrary
在iOS 9中已弃用,因此您可能需要考虑迁移到 PHPhotoLibrary
。
NS_CLASS_DEPRECATED_IOS(4_0, 9_0, "使用 PHPhotoLibrary from the Photos 框架代替") @interface ALAssetsLibrary : NSObject