簡體   English   中英

緩存圖像以供離線使用 SDWebImage

[英]Cache image for use offline SDWebImage

我正在使用 SDWebImage 從不同的 URL 下載圖像,現在我想知道是否可以下載這些圖像並將它們存儲在某個位置,這樣當我離線並啟動我的應用程序時,我仍然可以看到它們嗎?

我注意到 Instagram 使用了類似的東西,一旦你下載了圖像,你可以關閉應用程序離線,然后重新打開應用程序,你仍然可以看到圖像。

我認為這對 SDWebImage 是可能的,但不確定,如果不可能,請糾正我。

非常感謝任何可以提供幫助的人!

導入UIImageView+WebCache.h標頭,並在您的視圖控制器中調用setImageWithURL:placeholderImage:方法。 SDWebImage庫將為您處理,從異步下載到緩存管理。

我假設您要存檔的是那種提要,在您的應用程序被殺死/重新啟動后,您會顯示 4-5 張圖片,並且您沒有互聯網連接 - 就像 Instagram 那樣。

對您來說,一種可能性是,當您有互聯網連接時,按照習慣下載圖像,並將 4-5 個圖像作為 NSData 存儲到您的核心數據中。

然后您就可以將這些圖像用作占位符,並且在用戶沒有連接時您將擁有“內容”。

這是將圖像轉換為 NSData 並返回的代碼:

let dataFromImage = UIImagePNGRepresentation(image!)!
let imageFromData = UIImage(data: imageData)

這是一個關於如何將圖像存儲到核心數據的完美教程

然后,您可以使用核心數據中的圖像填充 tableView(例如),以防reachability == false

您可以使用SDWebImage將圖像存儲在應用程序目錄中,而不是手動存儲。 當您使用SDImageCache時,它會更簡單。 diskImageExistsWithKey確定您的圖像是否存在於位置(在應用程序的目錄或臨時文件夾中)。 您只需檢查一下! ...

[[SDImageCache sharedImageCache] diskImageExistsWithKey:localImagePath completion:^(BOOL isInCache) {
        if ( isInCache ) {
            image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:localPath]; // it returns a simple UIImage 
[yourImageView setImage:[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:localPath]]; // or set image in your UIImageView
        } else {
            [yourImageView sd_setImageWithURL:[NSURL URLWithString:downloadPath] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                if (image) {
                    [[SDImageCache sharedImageCache] storeImage:image forKey:localPath toDisk:YES completion:^{ // This block will help you to store image from server to local directiry
                        NSLog(@"Downloaded");
                    }];
                }
            }];
        }
    }] ;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM