美文网首页日常收录
ios15保存网络图片至本地相册

ios15保存网络图片至本地相册

作者: Johnson_9d92 | 来源:发表于2021-12-13 16:52 被阅读0次

ios15保存网络图片至本地相册

案例

主要源码:

//
//  ViewController.m
//  testSaveNetworkImage
//
//  Created by lujun on 2021/12/12.
//

#import "ViewController.h"
#define imageURL @"https://wx4.sinaimg.cn/mw690/c4994d69gy1gx4eakvm6vj22bk3404qs.jpg"

@interface ViewController ()
@property(nonatomic,weak)UIImageView *imageViewDemo;
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
       //耗时操作放在 多线程里面
        NSURL *url = [NSURL URLWithString:imageURL];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调UI页面的时候,回到主线程里面
            self.imageViewDemo.image = image;
         });
    });
}
-(void)savePhoto{
//    NSLog(@"%s",__func__);
    //对图片进行存储
    UIImageWriteToSavedPhotosAlbum(self.imageViewDemo.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
//    NSLog(@"%@",error);
    //对图片存储完,进行回调,提示用户,图片是否保存成功
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"保存用户提示" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    if(error){
        //失败
        NSLog(@"%@",@"失败");
        alertVC.message = @"保存失败";
    }else{
        //成功
        NSLog(@"%@",@"成功");
        alertVC.message = @"保存成功";
        
    }
    [self presentViewController:alertVC animated:YES completion:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dismissViewControllerAnimated:alertVC completion:nil];
        [self.imageViewDemo removeFromSuperview];
    });
}
#pragma 懒加载
- (UIImageView *)imageViewDemo{
    if(!_imageViewDemo){
        UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 50, [UIScreen mainScreen].bounds.size.width, 250)];
        [self.view addSubview:iv];
        //给UIImageView添加一个手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        [iv addGestureRecognizer:tap];
        iv.contentMode = UIViewContentModeScaleAspectFill;
        //允许用户交互
        [iv setUserInteractionEnabled:YES];
        [tap addTarget:self action:@selector(savePhoto)];
        self.imageViewDemo = iv;
    }
    return _imageViewDemo;
}
@end

相关文章

网友评论

    本文标题:ios15保存网络图片至本地相册

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