2012-04-03 145 views
0

我正在嘗試創建一個簡單的Twitter客戶端,並且延遲加載Twitter圖片。我可以在UITableView中獲取並顯示推文,但我無法加載圖像。延遲加載的Twitter個人資料圖片不起作用

這是我得到的,正確的文字和用戶名負載,但沒有圖像:

enter image description here

我想問題可能是這個方法,是通過委託圖像加載調用一次,並應顯示圖像在表格視圖單元格:

// Called by ImageDownloader when image is ready to be displayed 
- (void)imageDidLoad:(NSString *)downloadedImageUrl downloadedImage:(UIImage *)downloadedImage 
{ 
    for (Tweet *tweet in self.tweets) { 
     if (tweet.userProfileImageUrl == downloadedImageUrl) { 
      tweet.userProfileImage = downloadedImage; 
      UITableViewCell *tweetCell = [self.tableView cellForRowAtIndexPath:tweet.uiTableViewCellIndexPath]; 
      tweetCell.imageView.image = downloadedImage; 
     } 
    } 
} 

但我更貼我的代碼波紋管只是要確定...


我已經定義了一個簡單的類爲我的微博:

@interface Tweet : NSObject 
{ 
    NSString *userName; 
    NSString *text; 
    NSString *userProfileImageUrl; 
    UIImage *userProfileImage; 
    NSIndexPath *uiTableViewCellIndexPath; 
} 

@property (nonatomic, retain) NSString *userName; 
@property (nonatomic, retain) NSString *text; 
@property (nonatomic, retain) NSString *userProfileImageUrl; 
@property (nonatomic, retain) UIImage *userProfileImage; 
@property (nonatomic, retain) NSIndexPath *uiTableViewCellIndexPath; 
@end 

我也實現了一個簡單的圖片下載類:

@protocol ImageDownloaderDelegate 

- (void)imageDidLoad:(NSString *)downloadedImageUrl downloadedImage:(UIImage *)downloadedImage; 

@end 

@interface ImageDownloader : NSObject 
{ 
    NSString *imageUrl; 
    UIImage *downloadedImage; 
    id <ImageDownloaderDelegate> __unsafe_unretained delegate; 
    NSMutableData *activeDownload; 
    NSURLConnection *imageConnection; 
} 

@property (nonatomic, retain) NSString *imageUrl; 
@property (nonatomic, retain) UIImage *downloadedImage; 
@property (unsafe_unretained) id <ImageDownloaderDelegate> delegate; 
@property (nonatomic, retain) NSMutableData *activeDownload; 
@property (nonatomic, retain) NSURLConnection *imageConnection; 

- (void)startDownload; 
- (void)cancelDownload; 

@end 

使用這種實現:

#import "ImageDownloader.h" 

#define kImageWidth 48 
#define kImageHeight 48 

@implementation ImageDownloader 

@synthesize imageUrl; 
@synthesize downloadedImage; 
@synthesize delegate; 
@synthesize activeDownload; 
@synthesize imageConnection; 

#pragma mark 

- (void)startDownload 
{ 
    self.activeDownload = [NSMutableData data]; 
    self.imageConnection = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.imageUrl]] delegate:self]; 
} 

- (void)cancelDownload 
{ 
    [self.imageConnection cancel]; 
    self.imageConnection = nil; 
    self.activeDownload = nil; 
} 

#pragma mark - 
#pragma mark Download support (NSURLConnectionDelegate) 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    // Clear the activeDownload property to allow later attempts 
    self.activeDownload = nil; 

    // Release the connection now that it's finished 
    self.imageConnection = nil; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    // Set userProfileImage and clear temporary data/image 
    UIImage *image = [[UIImage alloc] initWithData:self.activeDownload]; 
    if (image.size.width != kImageWidth || image.size.height != kImageHeight) { 
     CGSize itemSize = CGSizeMake(kImageWidth, kImageHeight); 
     UIGraphicsBeginImageContext(itemSize); 
     CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height); 
     [image drawInRect:imageRect]; 
     self.downloadedImage = UIGraphicsGetImageFromCurrentImageContext(); 
     UIGraphicsEndImageContext(); 
    } else { 
     self.downloadedImage = image; 
    } 

    self.activeDownload = nil; 

    // Release the connection now that it's finished 
    self.imageConnection = nil; 

    // Call our delegate and tell it that our image is ready for display 
    [delegate imageDidLoad:self.imageUrl downloadedImage:self.downloadedImage]; 
} 

@end 

在我的主控制器我加載了推文:

// Fetch the Twitter timeline and assigns tweets to the tweets property 
- (void)fetchTweets 
{ 
    self.tweets = [[NSMutableArray alloc] init]; 

    NSString *userTimelineUrl = @"https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=richardknop&count=25"; 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:userTimelineUrl]]; 

     NSError *error; 

     NSArray *tweetJsonObjects = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
     for (NSUInteger i = 0; i < [tweetJsonObjects count]; i++) { 
      Tweet *tweet = [[Tweet alloc] init]; 
      tweet.userName = [[[tweetJsonObjects objectAtIndex:i] objectForKey:@"user"] objectForKey:@"name"]; 
      NSString * textString = [[tweetJsonObjects objectAtIndex:i] objectForKey:@"text"]; 
      tweet.text = textString; 
      tweet.userProfileImageUrl = [[[tweetJsonObjects objectAtIndex:i] objectForKey:@"user"] objectForKey:@"profile_image_url"]; 
      [self.tweets addObject:tweet]; 
     } 

     dispatch_async(dispatch_get_main_queue(), ^{ 
      [self.tableView reloadData]; 
     }); 

    }); 
} 

這是我如何加載表視圖的內容:

- (void)startImageDownload:(NSString *)userProfileImageUrl 
{ 
    BOOL downloadAlreadyInProgress = NO; 
    for (ImageDownloader *storedImageDownloader in self.imageDownloadsInProgress) { 
     if (storedImageDownloader.imageUrl == userProfileImageUrl) { 
      downloadAlreadyInProgress = YES; 
     } 
    } 

    if (downloadAlreadyInProgress == NO) { 
     ImageDownloader *imageDownloader = [[ImageDownloader alloc] init]; 
     imageDownloader.imageUrl = userProfileImageUrl; 
     imageDownloader.delegate = self; 
     [self.imageDownloadsInProgress addObject:imageDownloader]; 
     [imageDownloader startDownload]; 
    } 
} 

回答

1

要麼你刪除的代碼,因爲的重要組成部分:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    int count = [self.tweets count]; 
    return count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *cellIdentifier = @"TweetCell"; 

    UITableViewCell * tweetCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    if (tweetCell == nil) { 
     tweetCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier]; 
    } 

    if ([self.tweets count] > 0) { 

     Tweet *tweet = [self.tweets objectAtIndex:indexPath.row]; 
     tweet.uiTableViewCellIndexPath = indexPath; 

     tweetCell.textLabel.text = tweet.text; 
     tweetCell.detailTextLabel.text = tweet.userName; 

     // Only load cached images; defer new downloads until scrolling ends 
     if (!tweet.userProfileImage) { 
      if (self.tableView.dragging == NO && self.tableView.decelerating == NO) { 
       [self startImageDownload:tweet.userProfileImageUrl]; 
      } 
      // If a download is deferred or in progress, return a placeholder image 
      tweetCell.imageView.image = [UIImage imageNamed:@"Placeholder.png"]; 
     } else { 
      tweetCell.imageView.image = tweet.userProfileImage; 
     } 

    } 

    return tweetCell; 
} 

如果鳴叫圖片此方法啓動下載發帖時間太長或者您錯過了NSURLConnectionDataDelegate(以前稱爲NSURLConnectionDelegate)協議的最重要方法。你用實際數據填寫self.activeDownload

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    [self.activeDownload appendData:data]; 
} 
+0

這不是任何地方在這個例子中:http://developer.apple.com/library/ios/#samplecode/LazyTableImages/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009394-Intro- DontLinkElementID_2 – 2012-04-03 20:48:46

+0

我向ImageDownloader.m添加了這個功能 - 它工作正常:D謝謝,你真的很聰明。 – 2012-04-03 20:50:01

+0

它實際上是「IconDownloader.m」示例的一部分 - 第104行。但它對你有幫助。 :-) – 2012-04-03 21:11:56

相關問題