美文网首页
iOS 相册创建文件夹并对照片进行命名

iOS 相册创建文件夹并对照片进行命名

作者: calary | 来源:发表于2021-12-04 15:11 被阅读0次

    一、前言

    项目开发中遇到需要保存照片到特定文件夹的功能,并且图片还要自定义名称,因为平时都是直接保存使用还没有涉及过特定保存,所以这里记录下实现过程

    二、相册文件夹创建和保存

    -(PHAssetCollection *)getAssetCollectionAppNameAndCreate
    {
        //设置你想要创建的相册的名字
        NSString *title = @"自定义相册";
        //获取与要创建的相册同名的自定义相册
        PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
        for (PHAssetCollection *collection in collections) {
            //遍历
            if ([collection.localizedTitle isEqualToString:title]) {
                //找到了同名的自定义相册,返回
                return collection;
            }
        }
        //程序走到这,说明没有找到自定义的相册,需要创建
        NSError *error = nil;
        __block NSString *createID = nil; //用来获取创建好的相册
        [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
            //发起了创建新相册的请求,并拿到相册的id,当前并没有创建成功,待创建成功后,通过id来获取创建好的自定义相册
            PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
            createID = request.placeholderForCreatedAssetCollection.localIdentifier;
        } error:&error];
        if (error) {
            NSLog(@"创建失败");
            return nil;
        }else{
            NSLog(@"创建成功");
            //通过id获取创建完成的相册
            return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createID] options:nil].firstObject;
        }
    }
    
    -(PHFetchResult<PHAsset *> *)saveImageWithFileUrl:(NSString *)fileUrl
    {
        __block NSString *createdAssetID = nil;
        NSError *error = nil;
        [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
            //直接保存image,不可设置名称
    //        createdAssetID = [PHAssetChangeRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
            // 根据路径保存图片,可设置名称
            PHAssetCreationRequest *request = [PHAssetCreationRequest creationRequestForAsset];
            createdAssetID = request.placeholderForCreatedAsset.localIdentifier;
            PHAssetResourceCreationOptions *option = [[PHAssetResourceCreationOptions alloc] init];
            option.shouldMoveFile = YES;
            option.originalFilename = @"照片的名字啊";
            [request addResourceWithType:PHAssetResourceTypePhoto fileURL:[NSURL fileURLWithPath:fileUrl] options:option];
        } error:&error];
        if (error) {
            return nil;
        }
        //获取保存到系统相册成功后的 asset 对象集合(一张图片也是返回一个集合)
        PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsWithLocalIdentifiers:@[createdAssetID] options:nil];
        return assets;
    }
    
    // 保存到相册
    - (void)keepToAlbum {
        PHAssetCollection *assetCollection = [self getAssetCollectionAppNameAndCreate];
        if (assetCollection == nil) {
               NSLog(@"相册创建失败");
               return;
        }
        //将图片保存到系统的相册
        PHFetchResult<PHAsset *> *assets = [self saveImageWithFileUrl:self.fileUrl];
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            //选取自定义相册进行操作
            PHAssetCollectionChangeRequest *collectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
            //插入图片到自定义相册
            PHFetchResult<PHAsset *> *assetCount = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
            [collectionChangeRequest insertAssets:assets atIndexes:[NSIndexSet indexSetWithIndex:assetCount.count]];
            NSLog(@" 保存完成");
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
    
        }];
    }
    

    三、相册文件夹图片读取

    /// 获取文件夹
    -(PHAssetCollection *)getAssetCollectionAppName {
        //设置你想要创建的相册的名字, 和保存的时候名字相同即可获取到那个文件夹
        NSString *title = @"自定义相册";
        //获取与要创建的相册同名的自定义相册
        PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
        for (PHAssetCollection *collection in collections) {
            //遍历
            if ([collection.localizedTitle isEqualToString:title]) {
                //找到了同名的自定义相册,返回
                return collection;
            }
        }
        return nil;
    }
    
    // 加载图片
    - (void)loadPhotoes {
        PHAssetCollection *assetCollection = [self getAssetCollectionAppName];
        if (assetCollection == nil) {
               NSLog(@"相册创建失败");
               return;
        }
        PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
        //ascending为NO,即为逆序(由现在到过去), ascending为YES时即为默认排序,由远到近
        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO];
        fetchOptions.sortDescriptors = @[sort];
        PHFetchResult<PHAsset *> *assetCount = [PHAsset fetchAssetsInAssetCollection:assetCollection options:fetchOptions];
        for (int i = 0; i<assetCount.count; i++) {
            PHAsset *asset = assetCount[i];
            PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
            options.synchronous = YES;
            // iCloud图片
            options.networkAccessAllowed = YES;
            // 高清图
            options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
            [PHImageManager.defaultManager requestImageForAsset:asset targetSize:CGSizeMake(800, 400) contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
               // 第一种获取照片路径的方法
                NSString *fileUrl = [NSString stringWithFormat:@"%@",[info valueForKey:@"PHImageFileURLKey"]];
                NSArray<PHAssetResource *> *resources = [PHAssetResource assetResourcesForAsset:asset];
                PHAssetResource *firstResource = resources.firstObject;
              // 第二种获取照片路径的方法
                NSString *privateFileURL = [NSString stringWithFormat:@"%@",[firstResource valueForKey:@"privateFileURL"]];
                if (fileUrl.length <= 0 || [@"(null)" isEqualToString:fileUrl]) {
                    fileUrl = privateFileURL;
                }
               NSString *fileName = @"未命名";
               if (firstResource){
                    fileName = firstResource.originalFilename;
                }
               NSLog(@"fileName:%@", fileName);
              // 拿到了fileUrl 和 fileName,就可以根据自己的需要处理了
            }];
        }
        [self.tableView reloadData];
    }
    

    四、总结

    以上是照片文件夹创建和获取的情况,有问题大家可以评论区沟通

    相关文章

      网友评论

          本文标题:iOS 相册创建文件夹并对照片进行命名

          本文链接:https://www.haomeiwen.com/subject/itnvxrtx.html