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

 更新时间:2016年04月12日 09:06:30   作者:李刚  
这篇文章主要介绍了iOS保存App中的照片到系统相册或自建相册的方法,示例代码为传统的Objective-C语言写成,需要的朋友可以参考下

保存照片到系统相册
保存照片到系统相册这个功能很多社交类的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();
            }
        }
    }];
}

相关文章

  • iOS CoreMotion实现设备运动加速度计陀螺仪

    iOS CoreMotion实现设备运动加速度计陀螺仪

    这篇文章主要介绍了iOS CoreMotion实现设备运动加速度计陀螺仪,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • iOS本地推送简单实现代码

    iOS本地推送简单实现代码

    这篇文章主要为大家详细介绍了iOS本地推送简单实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-09-09
  • 深入分析iOS应用中对于图片缓存的管理和使用

    深入分析iOS应用中对于图片缓存的管理和使用

    这篇文章主要介绍了iOS应用中对于图片缓存的管理和使用,实例代码为传统的Objective-C,需要的朋友可以参考下
    2016-04-04
  • 讲解iOS开发中UITableView列表设计的基本要点

    讲解iOS开发中UITableView列表设计的基本要点

    这篇文章主要介绍了讲解iOS开发中UITableView列表设计的基本要点,其中对列表行操作的常用操作举例是iOS开发中经常用到的基础,需要的朋友可以参考下
    2016-01-01
  • 详解iOS App中UITableView的创建与内容刷新

    详解iOS App中UITableView的创建与内容刷新

    这篇文章主要介绍了iOS App中UITableView的创建与内容刷新,讲解了UITableView一些基本的样式与cell的设置及刷新,需要的朋友可以参考下
    2016-04-04
  • iOS APP 多服务器环境分离的方法

    iOS APP 多服务器环境分离的方法

    这篇文章主要介绍了iOS APP 多服务器环境分离的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-07-07
  • 浅谈SwiftUI 里面$0是什么意思如何用

    浅谈SwiftUI 里面$0是什么意思如何用

    这篇文章主要介绍了浅谈SwiftUI 里面$0是什么意思如何用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-01-01
  • ios 获取或修改网页上的内容

    ios 获取或修改网页上的内容

    UIWebView是iOS最常用的SDK之一,它有一个stringByEvaluatingJavaScriptFromString方法可以将javascript嵌入页面中,通过这个方法我们可以在iOS中与UIWebView中的网页元素交互
    2016-12-12
  • iOS中应用内添加指纹识别的实例代码

    iOS中应用内添加指纹识别的实例代码

    iOS8之后苹果发布了指纹识别的功能,通过touch ID来识别用户,做用户授权,主要是依赖于LocalAuthentication库,下面通过本文给大家介绍iOS中应用内添加指纹识别的实例代码,一起看看吧
    2016-12-12
  • iOS延迟执行方法详解

    iOS延迟执行方法详解

    这篇文章主要为大家详细介绍了iOS延迟执行方法,包括performSelector(NSObject)方法、NSTimer、GCD和sleep(NSThread)四种方法,需要的朋友可以参考下
    2016-11-11

最新评论