YouTube Embedded Videos in UITableViewCell: How to Cache to Prevent Reboot?

I embed YouTube video thumbnails in my UITableView Cell through the following code. However, whenever I look at the table, the thumbnails of the video reload when the cell leaves the screen and returns.

What is the most efficient way to cache 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;
}  
+5
source share
1 answer

In these situations, you can (after the first selection of the webView) associate the webView with the object in searchResultArray with the objc_setAssociatedObject.

, , cellFoRowAtIndexPath , , - , , :

objc_setAssociatedObject([searchResultArray valueForKey:someIndex], &someKey, webView, OBJC_ASSOCIATION_RETAIN_NONATOMIC)

cellForRowAtIndexPath:

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
}

webViews, . & someKey char .

0

All Articles