Reputation: 81
I'm new to iOS developing and have an silly problem I have an project to parse RSS feed and it all works fine but I tried to fetch images in the background to improve the UI and stuck on how to update the UIImageView in my TableView cells? Here the code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CustomCell";
MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.titleLabel.text = [[feeds objectAtIndex:indexPath.row] objectForKey:@"title"];
NSString* test = [[feeds objectAtIndex:indexPath.row] objectForKey:@"url"];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
initWithTarget:self
selector:@selector(doNow:)
object:test];
[queue addOperation:operation];
cell.myImages = theImagePropery;
return cell;
}
-(void)doNow:(NSString*)myData
{
NSString* url = myData;
url = [url stringByReplacingOccurrencesOfString:@" " withString:@""];
NSURL* imageURL = [NSURL URLWithString:url];
NSData* imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage* image = [[UIImage alloc]initWithData:imageData];
[self performSelectorOnMainThread:@selector(displayImage:) withObject:image waitUntilDone:NO];
}
Now in displayImage method I don't know what to do and thats my last try:
-(void)displayImage:(UIImage *)myImage{
[[self tableView] beginUpdates];
theImageProbery = [[UIImageView alloc] initWithImage:myImage];
[[self tableView] endUpdates];
What can I do?
Upvotes: 0
Views: 65
Reputation: 21497
Take a look at the LazyTableImages sample.
It's dated, and you can replace the IconDownloader class with NSURLSesssionDataTask, but it will give you the basic idea of how to structure your code.
Upvotes: 1
Reputation: 4551
Do not use the synchronous method dataWithContentsOfURL
to request network-based URLs.This method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience. Use the NSURLSession methods ( if your are targeting iOS 7 and later).
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler
or use the NSURLConnection
method (is you are targeting iOS 6 and later).
+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
PS : The best is to use open source librairies that handle all this for you ( downloading the images in a background thread, caching,..).
Upvotes: 1