使用异步请求以串行方式下载图像

时间:2014-07-25 17:17:49

标签: ios grand-central-dispatch nsoperationqueue

我想异步从服务器下载图像,但它们并不是连续出现的。当我发出同步请求时,它会连续下载,但会产生其他问题。

代码:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void){    
    NSString *UrlStr=urlString;

    NSURL *imageURL=[NSURL URLWithString:[UrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSData *tempData=[NSData dataWithContentsOfURL:imageURL];
    UIImage *imgData=[UIImage imageWithData:tempData];

    dispatch_async(dispatch_get_main_queue(), ^{

        if (tempData!=nil) {

            ((FXImageView *)view).image = imgData;
            [_images addObject:imgData];

        }
        else{
            ((FXImageView *)view).image = [UIImage imageNamed:@"NoImage.png"];
            [_images addObject:[UIImage imageNamed:@"NoImage.png"]];

        }

    });

})

我也试过NSOperationQueue但是没有成功。

2 个答案:

答案 0 :(得分:0)

dispatch_queue_t queue;
queue = dispatch_queue_create("com.example.MyQueue", NULL);

dispatch_async(queue, ^(void){    
NSString *UrlStr=urlString;

NSURL *imageURL=[NSURL URLWithString:[UrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *tempData=[NSData dataWithContentsOfURL:imageURL];
UIImage *imgData=[UIImage imageWithData:tempData];

dispatch_async(dispatch_get_main_queue(), ^{

    if (tempData!=nil) {

        ((FXImageView *)view).image = imgData;
        [_images addObject:imgData];

    }
    else{
        ((FXImageView *)view).image = [UIImage imageNamed:@"NoImage.png"];
        [_images addObject:[UIImage imageNamed:@"NoImage.png"]];

    }

});

})

https://developer.apple.com/library/ios/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html#//apple_ref/doc/uid/TP40008091-CH102-SW6

https://developer.apple.com/library/ios/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html#//apple_ref/doc/uid/TP40008091-CH102-SW5

不一样......我没有回复评论。我创建了一个串行队列,你使用了一个并发队列。按照链接来理解背后的理论。

答案 1 :(得分:0)

NSOperationQueue设置为maxConcurrentOperationCount的情况下尝试1,但请注意,在这种情况下,您应将图像下载实现为NSOperation子类。请查看NSOperation上的Apple documentation,了解如何实施异步NSOperation