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

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.framework)