美文网首页
iOS开发中,安装包中大Size的图片资源预先下载

iOS开发中,安装包中大Size的图片资源预先下载

作者: 左方 | 来源:发表于2024-04-09 16:37 被阅读0次
- (void)downloadImages {
    // 图片 URL 数组
    NSArray *imageURLs = @[@"https://pic1.*.com.cn/sign_in_1.png",
                           @"https://pic1.*.com.cn/sign_in_2.gif",
                           @"https://pic1.*.com.cn/sign_in_3.gif",
                           @"https://pic1.*.com.cn/sign_in_4.gif",
                           @"https://pic1.*.com.cn/sign_in_5.gif",
                           @"https://pic1.*.com.cn/sign_in_6.gif"];
    
    // 遍历图片 URL 数组并下载每个图片
    for (NSString *imageURLString in imageURLs) {
        NSURL *url = [NSURL URLWithString:imageURLString];
        
        // 检查本地是否已经存在相同的图片文件
        NSString *filename = [[url lastPathComponent] stringByDeletingPathExtension];
        NSString *fileExtension = [url pathExtension];
        NSString *fullFilename = [filename stringByAppendingPathExtension:fileExtension];
        
        NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
        NSURL *fileURL = [documentsURL URLByAppendingPathComponent:fullFilename];
        
        // 如果图片已存在本地,则跳过下载
        if ([[NSFileManager defaultManager] fileExistsAtPath:[fileURL path]]) {
            DDLogInfo(@"图片 %@ 已存在本地,跳过下载", fullFilename);
            continue;
        }
        
        NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            if (error) {
                DDLogInfo(@"下载图片 %@ 时发生错误:%@", imageURLString, error.localizedDescription);
                return;
            }
            
            // 保存图片到本地
            [self saveImageData:data fromURL:url];
        }];
        [task resume];
    }
}

- (void)saveImageData:(NSData *)imageData fromURL:(NSURL *)url {
    if (!imageData) {
        DDLogInfo(@"下载的数据为空");
        return;
    }
    
    // 获取图片文件名和文件扩展名
    NSString *filename = [[url lastPathComponent] stringByDeletingPathExtension];
    NSString *fileExtension = [url pathExtension];
    
    NSString *fullFilename = [filename stringByAppendingPathExtension:fileExtension];
    
    // 将图片数据保存到本地
    NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
    NSURL *fileURL = [documentsURL URLByAppendingPathComponent:fullFilename];
    
    NSError *error = nil;
    if (![imageData writeToURL:fileURL options:NSDataWritingAtomic error:&error]) {
        DDLogInfo(@"保存图片 %@ 到本地时发生错误:%@", fullFilename, error.localizedDescription);
    } else {
        DDLogInfo(@"图片 %@ 已保存到本地:%@", fullFilename, fileURL);
    }
}

在AppDelegate中调用下载图片方法。
然后在使用的地方使用如下代码:

            let filename = "sign_in_6.gif" // 你保存图片时指定的文件名
            guard let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
                print("无法获取Documents目录")
                return
            }
            let fileURL = documentsURL.appendingPathComponent(filename)
            
            // 从文件URL加载图片数据
            do {
                let imageData = try Data(contentsOf: fileURL)
                // 从图片数据创建UIImage对象
                if let image = UIImage(data: imageData) {
                    // 将图片设置到UIImageView中
                    todayImage.image = UIImage.gifImageData(imageData) 
                } else {
                    print("无法将数据转换为图片")
                }
            } catch {
                print("加载图片时出错:", error.localizedDescription)
            }

在UIImage中加上一个扩展,方便展示GIF

+ (UIImage *)gifImageData:(NSData*)data {
    CGImageSourceRef imgSource = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    if (!imgSource) {
        return [UIImage new];
    }
    
    NSMutableArray<UIImage *> *images = [NSMutableArray array];
    NSTimeInterval totalDuration = 0;
    size_t imageCount = CGImageSourceGetCount(imgSource);
    for (size_t i = 0; i < imageCount; i++) {
        CGImageRef cgImage = CGImageSourceCreateImageAtIndex(imgSource, i, NULL);
        if (!cgImage) {
            continue;
        }
        
        CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imgSource, i, NULL);
        if (!properties) {
            continue;
        }
        
        NSDictionary *gifDic = (__bridge NSDictionary *)CFDictionaryGetValue(properties, kCGImagePropertyGIFDictionary);
        if (!gifDic) {
            CFRelease(properties);
            continue;
        }
        
        NSNumber *duration = gifDic[(__bridge NSString *)kCGImagePropertyGIFDelayTime];
        if (!duration) {
            CFRelease(properties);
            continue;
        }
        
        totalDuration += duration.doubleValue;
        
        UIImage *image = [UIImage imageWithCGImage:cgImage];
        [images addObject:image];
        
        CFRelease(properties);
        CGImageRelease(cgImage);
    }
    
    CFRelease(imgSource);
    
    return [UIImage animatedImageWithImages:images duration:totalDuration] ?: [UIImage new];
}

相关文章

网友评论

      本文标题:iOS开发中,安装包中大Size的图片资源预先下载

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