Reputation: 7549
Now I have a custom cell with the image and label. Later I print these cells by:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:customCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! customCell
var url = NSURL(string: postCover[indexPath.row])
if let data = NSData(contentsOfURL: url!) {
cell.cellImage.image = UIImage(data: data)
}
var title = postTitle[indexPath.row]
cell.cellLabel.text = title
let indexPath = tableView.indexPathForSelectedRow()
return cell
}
and when I open an app and scroll it freezes. How can I fix this bug?
I read about it, that I must use async image loading in my tableView, but don't I load them async already?
I searched and think about it 4-5 days and nothing. Can anyone give me some tips, please?
Upvotes: 0
Views: 11370
Reputation: 3690
create a bridging header in swift.Import AFNetworking header files
and then find these method setImageWithURLRequest
cell.imageView.setImageWithURLRequest
you can call in these way
Upvotes: -1
Reputation: 21
You can use third part Library SDWebImage on gitHub . It`s base on Objective-C, and there is another Library Kingfisher which base on Swift. And maybe this is what you want.
Upvotes: 2
Reputation: 5967
You can schedule the downloading of image asynchronously for each cell using GCD as-
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:customCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! customCell
var url = NSURL(string: postCover[indexPath.row])
cell.imageView.image = nil;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^(void) {
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:parsedData[@"imageLR"]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
if (image) {
dispatch_async(dispatch_get_main_queue(), ^{
if (cell.tag == indexPath.row) {
cell.imageView.image = image;
[cell setNeedsLayout];
}
});
}
});
return cell
}
for Swift you can do so as
if let data = self.cache.objectForKey(urlString) as? NSData {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
let image = UIImage(data: data)
dispatch_async(dispatch_get_main_queue()) {
cell.imageView.image = image;
}
}
Upvotes: 2