iOS之圖片保存到相冊

不多說先看效果好不好
savecd.gif

下載網絡圖片的SDWebImage 還有加載圖片的DACircularProgress這兩個第三方庫
所以在控制器要到導入這兩個

import <UIImageView+WebCache.h>

import <DALabeledCircularProgressView.h>

這里是加載圖片主要代碼

 [self.picture sd_setImageWithURL:[NSURL URLWithString:@"http://wimg.spriteapp.cn/ugc/2016/11/09/5822a9157534a.gif"] placeholderImage:nil options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        // receivedSize : 已經接收的圖片大小
        // expectedSize : 圖片的總大小
        //  LYWLog(@"已經接收的圖片大小:%ld? ========== 圖片的總大小 %ld",receivedSize,expectedSize);
        
        CGFloat progress = 1.0 * receivedSize / expectedSize;
        self.progressView.trackTintColor = [UIColor grayColor];
        self.progressView.progress = progress;
        self.progressView.hidden = NO;
        self.progressView.progressLabel.text = [NSString stringWithFormat:@"%.0f%%", progress * 100];
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        self.progressView.hidden = YES;
    }];

保存到相冊的主要代碼

這里使用到 <Photos/Photos.h>這個系統(tǒng)的這個庫

/*
     PHAuthorizationStatusNotDetermined,     用戶還沒有做出選擇
     PHAuthorizationStatusDenied,            用戶拒絕當前應用訪問相冊(用戶當初點擊了"不允許")
     PHAuthorizationStatusAuthorized         用戶允許當前應用訪問相冊(用戶當初點擊了"好")
     PHAuthorizationStatusRestricted,        因為家長控制, 導致應用無法方法相冊(跟用戶的選擇沒有關系)
     */
    
    // 判斷授權狀態(tài)
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted) { // 因為家長控制, 導致應用無法方法相冊(跟用戶的選擇沒有關系)
        [SVProgressHUD showErrorWithStatus:@"因為系統(tǒng)原因, 無法訪問相冊"];
    } else if (status == PHAuthorizationStatusDenied) { // 用戶拒絕當前應用訪問相冊(用戶當初點擊了"不允許")
        NSLog(@"提醒用戶去[設置-隱私-照片-xxx]打開訪問開關");
    } else if (status == PHAuthorizationStatusAuthorized) { // 用戶允許當前應用訪問相冊(用戶當初點擊了"好")
        [self saveImage];
    } else if (status == PHAuthorizationStatusNotDetermined) { // 用戶還沒有做出選擇
        // 彈框請求用戶授權
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) { // 用戶點擊了好
                [self saveImage];
            }
        }];
    }
}

- (void)saveImage
{
    // PHAsset : 一個資源, 比如一張圖片\一段視頻
    // PHAssetCollection : 一個相簿
    
    // PHAsset的標識, 利用這個標識可以找到對應的PHAsset對象(圖片對象)
    __block NSString *assetLocalIdentifier = nil;
    
    // 如果想對"相冊"進行修改(增刪改), 那么修改代碼必須放在[PHPhotoLibrary sharedPhotoLibrary]的performChanges方法的block中
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        // 1.保存圖片A到"相機膠卷"中
        // 創(chuàng)建圖片的請求
        assetLocalIdentifier = [PHAssetCreationRequest creationRequestForAssetFromImage:self.picture.image].placeholderForCreatedAsset.localIdentifier;
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (success == NO) {
            [self showError:@"保存圖片失敗!"];
            return;
        }
        
        // 2.獲得相簿
        PHAssetCollection *createdAssetCollection = [self createdAssetCollection];
        if (createdAssetCollection == nil) {
            [self showError:@"創(chuàng)建相簿失敗!"];
            return;
        }
        
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            // 3.添加"相機膠卷"中的圖片A到"相簿"D中
            
            // 獲得圖片
            PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil].lastObject;
            
            // 添加圖片到相簿中的請求
            PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:createdAssetCollection];
            
            // 添加圖片到相簿
            [request addAssets:@[asset]];
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (success == NO) {
                [self showError:@"保存圖片失敗!"];;
            } else {
                [self showSuccess:@"保存圖片成功!"];;
            }
        }];
    }];
}

/**
 *  獲得相簿
 */
- (PHAssetCollection *)createdAssetCollection
{
    // 從已存在相簿中查找這個應用對應的相簿
    PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *assetCollection in assetCollections) {
        if ([assetCollection.localizedTitle isEqualToString:LYWAssetCollectionName]) {
            return assetCollection;
        }
    }
    
    // 沒有找到對應的相簿, 得創(chuàng)建新的相簿
    
    // 錯誤信息
    NSError *error = nil;
    
    // PHAssetCollection的標識, 利用這個標識可以找到對應的PHAssetCollection對象(相簿對象)
    __block NSString *assetCollectionLocalIdentifier = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        // 創(chuàng)建相簿的請求
        assetCollectionLocalIdentifier = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:LYWAssetCollectionName].placeholderForCreatedAssetCollection.localIdentifier;
    } error:&error];
    
    // 如果有錯誤信息
    if (error) return nil;
    
    // 獲得剛才創(chuàng)建的相簿
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[assetCollectionLocalIdentifier] options:nil].lastObject;
}

- (void)showSuccess:(NSString *)text
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showSuccessWithStatus:text];
    });
}

- (void)showError:(NSString *)text
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showErrorWithStatus:text];
    });
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容