Embedded YouTube Videos in UITableViewCell: How to cache to prevent reload?
I am embedding youtube video thumbnails in my UITableView Cell via the following code. However, whenever I scroll the table, the video thumbnails will reload when the cell leaves the screen and returns.
What is the most efficient way to cache the thumbnails so that they only load for the first time?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* PlaceholderCellIdentifier = @"PlaceholderCell";
SearchResult *searchResult = [self.searchResultArray objectAtIndex:indexPath.row];
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier开发者_运维知识库];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:PlaceholderCellIdentifier]autorelease];
UIWebView *videoView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 104, 104)];
videoView.tag = 1;
cell.imageView.image = [UIImage imageNamed:@"Placeholder"];
[cell.contentView addSubview:videoView];
[videoView release];
}
UIWebView *thisVideoView = (UIWebView *)[cell.contentView viewWithTag:1];
NSString *videoHTML = [self embedYouTube:searchResult.url frame:CGRectMake(0, 0, 104, 104)];
[thisVideoView loadHTMLString:videoHTML baseURL:nil];
return cell;
}
- (NSString*)embedYouTube:(NSString*)url frame:(CGRect)frame {
NSString* embedHTML = @"\
<html><head>\
<style type=\"text/css\">\
body {\
background-color: transparent;\
color: white;\
}\
</style>\
</head><body style=\"margin:0\">\
<embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
width=\"%0.0f\" height=\"%0.0f\"></embed>\
</body></html>";
NSString* html = [NSString stringWithFormat:embedHTML, url, frame.size.width, frame.size.height];
return html;
}
In theese situations you can (after first allocating webView) associate the webView with object in the searchResultArray with objc_setAssociatedObject.
The point is, since the cellFoRowAtIndexPath is called every time the cell becomes visible, that you should not initialize the webview there, but when you initialize them you do:
objc_setAssociatedObject([searchResultArray valueForKey:someIndex], &someKey, webView, OBJC_ASSOCIATION_RETAIN_NONATOMIC)
and then in cellForRowAtIndexPath you do:
if (objc_getAssociatedObject([searchResultArray valueForKey:indexPath.row, &someKey) != nil) {
UIWebView *thisVideoView = (UIWebView *)[cell.contentView viewWithTag:1];
*thisVideoView = objc_getAssociatedObject([searchResultArray valueForKey:indexPath.row, &someKey);
} else {
////empty webView or some loading indicator
}
You can initialize the webViews whenever you are ready to. &someKey is static char and must be global to the class.
精彩评论