你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS保存App中的照片到系統相冊或自建相冊的方法

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

編輯:IOS開發綜合

保存照片到系統相冊
保存照片到系統相冊這個功能很多社交類的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();
            }
        }
    }];
}

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved