您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 實戰:tableView 圖片的異步緩存加載

編輯:iOS 開發綜合

在 tableView 中加載大量圖片時,若每次都從網絡拉取會嚴重影響流暢度。實務上的做法是:有緩存則直接加載,無緩存則請求圖片、緩存下來後再加載。以下示範如何封裝這樣一個異步緩存加載的方案。

1. 建立基礎 ViewController

首先定義一個 ICTableViewDelegate 協議,用於在圖片加載完成後回調。.h 文件如下:

#define KimageKey @"photoFileUrl"   // 數組中每個 item 存放圖片 URL 的 key
#define KidKey @"activityId"        // 數組中每個 item 的 id,用於緩存

#import 
@protocol ICTableViewDelegate
@required
- (void)cellImageDidLoad:(NSIndexPath *)indexPath image:(NSMutableArray *)imageArray;
@end

@interface ICTableViewController : UIViewController 
{
  @public
    id  ICTableViewDelegate;
    NSMutableArray *tableDataArray;
    UITableView *wqTable;
}
@end

核心方法:加載或緩存圖片

loadCellImage 方法負責判斷圖片是否有緩存,並據此加載或下載:

- (void)loadCellImage {
    // 有緩存則加載圖片,無緩存則請求圖片並緩存後再加載
    NSArray *indexPathsForLoad = [wqTable indexPathsForVisibleRows];
    for (NSIndexPath *item in indexPathsForLoad) {
        NSInteger rowNumberForCell = item.row;
        if (rowNumberForCell > [tableDataArray count] - 1) {
            return;
        }
        NSString *imageStr = tableDataArray[rowNumberForCell][@"photoFileUrl"];
        NSMutableArray *imageArray = [NSMutableArray array];
        if ([imageStr length] != 0) {
            NSArray *photoUrl = [imageStr componentsSeparatedByString:MULTI_FILES_SEPARATOR];
            for (int i = 0; i < photoUrl.count; i++) {
                NSString *imageName = [tableDataArray[rowNumberForCell][KimageKey] stringByAppendingString:@".temp"];
                NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:imageName]];
                NSData *imageData = [NSData dataWithContentsOfFile:imageDataPath];
                if (imageData) {
                    UIImage *image = [UIImage imageWithData:imageData];
                    [imageArray addObject:image];
                } else {
                    // 無緩存則從網絡下載
                    NSString *url = photoUrl[i];
                    NSURL *nsurl = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                    NSData *data = [NSData dataWithContentsOfURL:nsurl];
                    if (data) {
                        [data writeToFile:imageDataPath atomically:YES];
                        UIImage *image = [UIImage imageWithData:data];
                        [imageArray addObject:image];
                    }
                }
            }
            // 回調代理,通知圖片加載完成
            if ([self.delegate respondsToSelector:@selector(cellImageDidLoad:image:)]) {
                [self.delegate cellImageDidLoad:item image:imageArray];
            }
        }
    }
}

2. 子類實現代理方法

具體的子類繼承這個父類,並實現 ICTableViewDelegate 代理方法,將加載好的圖片設置到對應的 cell 上:

#pragma mark ICTableViewDelegate
- (void)cellImageDidLoad:(NSIndexPath *)indexPath image:(NSMutableArray *)imageArray {
    EventShowTableViewCell *cell = (EventShowTableViewCell *)[_eventListTableView cellForRowAtIndexPath:indexPath];
    if ([imageArray count] != 0) {
        for (int i = 0; i < imageArray.count; i++) {
            CustomPhotoBtn *photoBtn;
            if (i == 0) {
                photoBtn = [CustomPhotoBtn customPhotoBtn];
            } else {
                photoBtn = (CustomPhotoBtn *)[cell.contentView viewWithTag:(i + 1) * 10];
            }
            UIImage *thumbImg = [FileTransferHelp thumbnailWithImage:(UIImage *)imageArray[i] size:CGSizeMake(60, 40)];
            [photoBtn.imgView setImage:thumbImg];
            [cell.contentView addSubview:photoBtn];
        }
    }
}

3. 在 cellForRowAtIndexPath 中設置內容

在子類設置每個 cell 內容的 cellForRowAtIndexPath: 方法中,先從緩存中查找圖片:

CustomPhotoBtn *photoBtn = [CustomPhotoBtn customPhotoBtn];
[photoBtn.fileFullName setText:url];
NSString *imageName = [url stringByAppendingString:@".temp"];
NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:imageName]];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageDataPath]];
UIImage *thumbImg = [FileTransferHelp thumbnailWithImage:image size:CGSizeMake(60, 40)];
if (thumbImg) {
    [photoBtn.imgView setImage:thumbImg];
}
return photoBtn;

透過「緩存優先、網絡補充」的策略搭配代理回調刷新,就能讓 tableView 在滾動時流暢地展示圖片,大幅改善使用者體驗。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved