开发文档iOS学习iOS学习笔记

iOS中的photos框架使用

2017-06-08  本文已影响113人  377f66eb43c9

最近工作中有一个需求:把应用上图片保存到手机相册中。

因为photos是xcode内置框架,所以只需要导入框架头文件即可。

#import <Photos/Photos.h>

下面介绍一下框架常用类。

核心类: PHPhotoLibrary

提供用户相册的与外界的数据交互的方法。这个框架在使用的流程上是比较麻烦的。凡是涉及到照片或者相册的增删改查的操作都是要拿到[PHPhotoLibrary sharedPhotoLibrary]并执行实例方法,在实例方法的changeBlock中进行。

- (void)performChanges:(dispatch_block_t)changeBlock completionHandler:(nullable void(^)(BOOL success, NSError*__nullable error))completionHandler;

- (BOOL)performChangesAndWait:(dispatch_block_t)changeBlock error:(NSError *__autoreleasing *)error;

上述两个方法的区别在于,第一个是异步执行,第二个是同步执行。因为这里不涉及网络数据传输,所以本文采取同步执行。

其它关键类: PHAsset(照片),PHAssetCollection(相册),PHAssetCollectionChangeRequest(修改相册时使用) ,PHAssetChangeRequest(修改相片时使用)...

获取自定义相册(没有时创建)

-(PHAssetCollection *)assetCollection{
    NSString *softTitle = [NSBundle mainBundle].infoDictionary[(NSString *)kCFBundleNameKey];
    PHAssetCollection *resultCollection = nil;
    PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];//获取相册,两个参数分别为系统枚举值,表示拿到的相册类型。
    for (PHAssetCollection *collection in collections) {
        if ([collection.localizedTitle isEqualToString:softTitle]) {
            resultCollection = collection;
            break;
        }
    }
    if (resultCollection == nil) {
        NSError *error = nil;
        __block NSString *creatAssetCollectionID = nil;
        [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
            creatAssetCollectionID = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:softTitle].placeholderForCreatedAssetCollection.localIdentifier;//在相册替身中取出id
        } error:&error];
        resultCollection = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[creatAssetCollectionID] options:nil].firstObject;
        
    }
    return resultCollection;
}

核心代码

- (IBAction)savePicture:(id)sender {
    //需要获取用户有没有授权
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
   
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (status == PHAuthorizationStatusDenied && oldStatus != PHAuthorizationStatusNotDetermined) {
                [SVProgressHUD showWithStatus:@"请打开权限"];
            }else if (status == PHAuthorizationStatusAuthorized){
                //1 获取照片
                NSError *error = nil;
                __block PHObjectPlaceholder *placeHolder = nil;
                [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
                    placeHolder = [PHAssetChangeRequest creationRequestForAssetFromImage:self.bigPictureImageView.image].placeholderForCreatedAsset;
                } error:&error];
                if (error) {
                    [SVProgressHUD showErrorWithStatus:@"获取图片失败"];
                }
                //2 获取相册,并且把相片添加到自定义相册
                PHAssetCollection *coll = [self assetCollection];
                [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
                    PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:coll];
                    [request addAssets:@[placeHolder]];
                } error:&error];
                if (error) {
                    [SVProgressHUD showErrorWithStatus:@"保存失败"];
                }else{
                    [SVProgressHUD showSuccessWithStatus:@"保存成功"];
                }
                
            }else if(status == PHAuthorizationStatusRestricted){
                [SVProgressHUD showErrorWithStatus:@"因系统原因,无法打开相册"];
            }

        });

    }];
}

上一篇下一篇

猜你喜欢

热点阅读