服务器之家

服务器之家 > 正文

iOS保存App中的照片到系统相册或自建相册的方法

时间:2021-01-15 16:08     来源/作者:李刚

保存照片到系统相册
保存照片到系统相册这个功能很多社交类的APP都有的,今天我们简单讲解一下,如何将图片保存到系统相册(Photo Album)。

1.创建UIImageView

创建UIImageView是为了将照片展示出来,我们是要把UIImage保存到系统相册(Photo Album):

复制代码 代码如下:


#define SCREEN [UIScreen mainScreen].bounds.size

 

self.image = [UIImage imageNamed:@"iOSDevTip"];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN.width - 300) / 2, 70, 300, 150)];
imageView.image = self.image;
[self.view addSubview:imageView];

 

2.创建UIButton

创建UIButton并绑定actionClick:事件:

复制代码 代码如下:


UIButton *button = [[UIButton alloc] init];
button.frame = CGRectMake( 100, 300, SCREEN.width - 200, 40);
[button addTarget:self action:@selector(actionClick:) forControlEvents:UIControlEventTouchUpInside];
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor orangeColor]];
[button setTitle:@"SavePhoto" forState:UIControlStateNormal];
[self.view addSubview:button];

 


- (void)actionClick:(UIButton *)button
{

}

 

3.保存照片到系统相册(Photo Album)

在actionClick:方法里调用:

复制代码 代码如下:

UIImageWriteToSavedPhotosAlbum(self.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);


这个时候,我们想知道保存是否成功,所以需要制定回调方法

复制代码 代码如下:

// 指定回调方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if(!error){
        NSLog(@"save success");
    }else{
        NSLog(@"save failed");
    }
}


在这个方法里,我们就知道照片是否保存成功。

 

 

保存照片到自己创建的相簿

接下来,我们来详细讲解一下关于系统相册权限获取、保存照片、创建自己的相簿等等功能。

1.创建自己的相簿

这也是一种比较创建的作法,创建自己的相簿,然后把照片或者视频保存到自己的相簿中。相关代码如下:

复制代码 代码如下:


  ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library addAssetsGroupAlbumWithName:@"test" resultBlock:^(ALAssetsGroup *group) {

 

    //创建相簿成功

} failureBlock:^(NSError *error) {
    //失败
}];


2.保存照片

 

这个方法也是将照片保存到系统相簿里面,不是保存到自己创建的相簿里面。代码如下:

复制代码 代码如下:


 ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
[library writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation)image.imageOrientation completionBlock:^(NSURL *asSetUrl,NSError *error){
    if (error) {
       //失败
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"存储成功"
                                                       message:nil
                                                      delegate:nil
                                             cancelButtonTitle:@"确定"
                                             otherButtonTitles:nil, nil];
        [alert show];

 

    }
}];


3.获取权限
在保存照片之前,如果用户关闭相册权限,这个时候是保存失败的。如果你不做任何处理,用户是不会知道自己保存失败了。所以,我们可以在保存照片之前,做出相应的提示。如何获取这个权限呢?一般有两种方法:

 

(1)创建相簿失败

(2)保存照片失败

在上面两个方法创建自己的相簿和保存照片的失败结果里,我们可以弹出获取照片权限失败的提示。我们拿第一个创建相簿失败来举例:

复制代码 代码如下:


ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library addAssetsGroupAlbumWithName:@"test" resultBlock:^(ALAssetsGroup *group)    {

 

      //创建相簿成功

} failureBlock:^(NSError *error) {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"存储失败"
                                                       message:@"请打开 设置-隐私-照片 来进行设置"
                                                      delegate:nil
                                             cancelButtonTitle:@"确定"
                                             otherButtonTitles:nil, nil];
    [alert show];
}];


在保存照片失败的结果里,我们也可以弹出相应的提示,让用户打开应用程序的相册权限。

 

4.保存照片到自己的相簿

下面这段代码是在大谷歌里面找到的,亲自测试过是可以用的,整理如下:

复制代码 代码如下:


#pragma mark - 创建相册
- (void)createAlbum
{
    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
    NSMutableArray *groups=[[NSMutableArray alloc]init];
    ALAssetsLibraryGroupsEnumerationResultsBlock listGroupBlock = ^(ALAssetsGroup *group, BOOL *stop)
    {
        if (group)
        {
            [groups addObject:group];
        }

 

        else
        {
            BOOL haveHDRGroup = NO;

            for (ALAssetsGroup *gp in groups)
            {
                NSString *name =[gp valueForProperty:ALAssetsGroupPropertyName];

                if ([name isEqualToString:@"iOSDevTip"])
                {
                    haveHDRGroup = YES;
                }
            }

            if (!haveHDRGroup)
            {
                //do add a group named "XXXX"
                [assetsLibrary addAssetsGroupAlbumWithName:@"iOSDevTip"
                                               resultBlock:^(ALAssetsGroup *group)
                 {
                     [groups addObject:group];

                 }
                                              failureBlock:nil];
                haveHDRGroup = YES;
            }
        }

    };
    //创建相簿
    [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAlbum usingBlock:listGroupBlock failureBlock:nil];

    [self saveToAlbumWithMetadata:nil imageData:UIImagePNGRepresentation(self.image) customAlbumName:@"iOSDevTip" completionBlock:^
     {
         //这里可以创建添加成功的方法

     }
                     failureBlock:^(NSError *error)
     {
         //处理添加失败的方法显示alert让它回到主线程执行,不然那个框框死活不肯弹出来
         dispatch_async(dispatch_get_main_queue(), ^{

             //添加失败一般是由用户不允许应用访问相册造成的,这边可以取出这种情况加以判断一下
             if([error.localizedDescription rangeOfString:@"User denied access"].location != NSNotFound ||[error.localizedDescription rangeOfString:@"用户拒绝访问"].location!=NSNotFound){
                 UIAlertView *alert=[[UIAlertView alloc]initWithTitle:error.localizedDescription message:error.localizedFailureReason delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) otherButtonTitles: nil];

                 [alert show];
             }
         });
     }];
}

- (void)saveToAlbumWithMetadata:(NSDictionary *)metadata
                      imageData:(NSData *)imageData
                customAlbumName:(NSString *)customAlbumName
                completionBlock:(void (^)(void))completionBlock
                   failureBlock:(void (^)(NSError *error))failureBlock
{

    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
    __weak ALAssetsLibrary *weakSelf = assetsLibrary;
    void (^AddAsset)(ALAssetsLibrary *, NSURL *) = ^(ALAssetsLibrary *assetsLibrary, NSURL *assetURL) {
        [assetsLibrary assetForURL:assetURL resultBlock:^(ALAsset *asset) {
            [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {

                if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:customAlbumName]) {
                    [group addAsset:asset];
                    if (completionBlock) {
                        completionBlock();
                    }
                }
            } failureBlock:^(NSError *error) {
                if (failureBlock) {
                    failureBlock(error);
                }
            }];
        } failureBlock:^(NSError *error) {
            if (failureBlock) {
                failureBlock(error);
            }
        }];
    };
    [assetsLibrary writeImageDataToSavedPhotosAlbum:imageData metadata:metadata completionBlock:^(NSURL *assetURL, NSError *error) {
        if (customAlbumName) {
            [assetsLibrary addAssetsGroupAlbumWithName:customAlbumName resultBlock:^(ALAssetsGroup *group) {
                if (group) {
                    [weakSelf assetForURL:assetURL resultBlock:^(ALAsset *asset) {
                        [group addAsset:asset];
                        if (completionBlock) {
                            completionBlock();
                        }
                    } failureBlock:^(NSError *error) {
                        if (failureBlock) {
                            failureBlock(error);
                        }
                    }];
                } else {
                    AddAsset(weakSelf, assetURL);
                }
            } failureBlock:^(NSError *error) {
                AddAsset(weakSelf, assetURL);
            }];
        } else {
            if (completionBlock) {
                completionBlock();
            }
        }
    }];
}

 

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部