美文网首页
iOS保存Gif图片和静态图片使用Photos.framewor

iOS保存Gif图片和静态图片使用Photos.framewor

作者: 智狸 | 来源:发表于2019-05-12 12:36 被阅读0次

iOS保存Gif图片和静态图片使用Photos.framework

copy就能用

源码:

- (void)saveImage {

    __blockNSString*createdAssetID =nil;

    NSError*error =nil;

    NSURL *fileUrl = [NSURL URLWithString:@"http://img.soogif.com/9yvNNmwwz0Sc5uuZ8bGPV8nkU2PAN1m8.gif"];

    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:fileUrl]];

    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{

        createdAssetID = [PHAssetChangeRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;

    }error:&error];

    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{

        PHAssetChangeRequest *changeAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];

        PHAssetCollection *targetCollection = [[PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil] lastObject];

        PHAssetCollectionChangeRequest *changeCollectionRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:targetCollection];

        PHObjectPlaceholder*assetPlaceholder = [changeAssetRequestplaceholderForCreatedAsset];

        [changeCollectionRequestaddAssets:@[assetPlaceholder]];

    }completionHandler:^(BOOLsuccess,NSError*_Nullableerror) {

        NSLog(@"finished adding.");

    }];

}

- (void)saveGifImage {

    NSURL *fileUrl = [NSURL URLWithString:@"http://img.soogif.com/9yvNNmwwz0Sc5uuZ8bGPV8nkU2PAN1m8.gif"];

    [[[NSURLSession sharedSession] downloadTaskWithURL:fileUrl completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        NSLog(@"%@", location);

        NSData *data = [NSData dataWithContentsOfFile:location.path];

        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{

            [[PHAssetCreationRequest creationRequestForAsset] addResourceWithType:PHAssetResourceTypePhoto data:data options:nil];

        }completionHandler:^(BOOLsuccess,NSError*_Nullableerror) {

            if(success && !error) {

                NSLog(@"下载成功");

            }else{

                NSLog(@"下载失败");

            }

        }];

    }]resume];

}

- (void)requestAuthorization {

    NSLog(@"%ld", [PHPhotoLibrary authorizationStatus]);

    if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {

//        [self saveGifImage];

        [selfsaveImage];

    }else{

        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {

//            [self saveGifImage];

            [selfsaveImage];

        }];

    }

}

相关文章

网友评论

      本文标题:iOS保存Gif图片和静态图片使用Photos.framewor

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