欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-12-10 21:52:28
保存照片到系统相册 保存照片到系统相册这个功能很多社交类的app都有的,今天我们简单讲解一下,如何将图片保存到系统相册(photo album)。 1.创建uiimag...

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