iOS 9.0之后照片支持gif的展示了,简介一下保存gif图的方法 和加载gif图的方法

保存 gif 图


//保存图片
- (void)saveImageWithData:(NSData *)imageData{
    if ([UIDevice currentDevice].systemVersion.floatValue >= 9.0f) {
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{

        PHAssetResourceCreationOptions *options = [[PHAssetResourceCreationOptions 
        alloc] init];
        [[PHAssetCreationRequest creationRequestForAsset] 
        addResourceWithType:PHAssetResourceTypePhoto
         data:[common getNSDataFromUrl:imageUrl] options:options];
        } completionHandler:^(BOOL success, NSError * _Nullable error) {

            [self image:nil didFinishSavingWithError:error contextInfo:nil];

        }];

    }else {
        UIImageWriteToSavedPhotosAlbum([UIImage imageWithData:
        [common getNSDataFromUrl:imageUrl]], 
        self, 
        @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }

}

//保存之后的提示方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
contextInfo:(void *)contextInfo
{
    if (error != NULL)
    {
    NSString *message;
    if (error.code ==-3310) {
        message = @"请到设置隐私开启相册权限";
    }else{
        message = @"保存失败";
    }
        [NSObject toastMessage:message];
    }
    else  // No errors
    {
        [NSObject toastMessage:@"已保存至手机相册"];
    }
}

获取gif图片资源的方法

- (void)getImage{
    PHImageManager * manager =[PHImageManager defaultManager];
    PHImageRequestOptions * ops =[[PHImageRequestOptions alloc]init];

    PHAsset * asset = [self.dataArray objectAtIndex:indexPath.row];
    // 下面的回调会返回多次 该属性设置YES 只返回一次,返回的是原图
    ops.synchronous = YES;
    ops.resizeMode = PHImageRequestOptionsResizeModeExact;

    [manager requestImageDataForAsset:asset options:ops
     resultHandler:^(NSData * _Nullable imageData,
      NSString * _Nullable dataUTI, 
      UIImageOrientation orientation,
       NSDictionary * _Nullable info) {
        if (imageData.length){

        //gif 图片
        if ([dataUTI isEqualToString:(__bridge NSString *)kUTTypeGIF]) {
            //这里获取gif图片的NSData数据
            _gifImageData = imageData;
        }
        else {
            //其他格式的图片
            returnImage = [UIImage imageWithData:imageData];

        }

    }else{
        //如果没有获取到imagedata,尝试直接获取图片
        [manager requestImageForAsset:asset targetSize:AssetGridThumbnailSize 
        contentMode:PHImageContentModeAspectFill options:ops
         resultHandler:^(UIImage * result, NSDictionary * info) {
            if (result) {
                returnImage = result;
            }
        }];
    }
}