iOS如何限制ASIHTTPRequest同时连接数?

时间:2013-12-02 09:16:19

标签: ios concurrency asihttprequest throttling

我正在开发一个RSS阅读器,它使用ASIHTTPRequest以异步方式下载每个Feed的帖子。

在初始运行期间,很多连接同时发生,即使我使用3-MOC解决方案(专用于写入 - >主要用于UI - >私有用于数据版本),它似乎也会冻结用户界面。 / p>

我想知道如何限制ASIHTTPRequest类将同时连接的数量限制为... 2或4而不是(我在调试器中看到它)一次数十个。

1 个答案:

答案 0 :(得分:1)

使用您自己创建的ASINetworkQueue可以更好地控制异步请求。使用队列时,只能同时运行一定数量的请求。如果您添加的请求多于队列的maxConcurrentOperationCount属性,请求将在其启动之前等待其他人完成。

显示如何使用ASIHTTPRequest管理队列的示例:

#import <Foundation/Foundation.h>
#import <GHUnit/GHUnit.h>
@class ASINetworkQueue;

@interface MyController : NSObject {
    ASINetworkQueue *networkQueue;

}

- (void)doNetworkOperations;

@property (retain) ASINetworkQueue *networkQueue;

@end

-------------------------------------------------------------------

#import "MyController.h"
#import "ASIHTTPRequest.h"
#import "ASINetworkQueue.h"

@implementation MyController

- (void)dealloc
{
    [networkQueue release];
    [super dealloc];
}

- (void)doNetworkOperations
{
    // Stop anything already in the queue before removing it
    [[self networkQueue] cancelAllOperations];

    // Creating a new queue each time we use it means we don't have to worry about clearing delegates or resetting progress tracking
    [self setNetworkQueue:[ASINetworkQueue queue]];
    [[self networkQueue] setDelegate:self];
    [[self networkQueue] setRequestDidFinishSelector:@selector(requestFinished:)];
    [[self networkQueue] setRequestDidFailSelector:@selector(requestFailed:)];
    [[self networkQueue] setQueueDidFinishSelector:@selector(queueFinished:)];

    int i;
    for (i=0; i<5; i++) {
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com"]];
        [[self networkQueue] addOperation:request];
    }

    [[self networkQueue] go];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    // You could release the queue here if you wanted
    if ([[self networkQueue] requestsCount] == 0) {

        // Since this is a retained property, setting it to nil will release it
        // This is the safest way to handle releasing things - most of the time you only ever need to release in your accessors
        // And if you an Objective-C 2.0 property for the queue (as in this example) the accessor is generated automatically for you
        [self setNetworkQueue:nil]; 
    }

    //... Handle success
    NSLog(@"Request finished");
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    // You could release the queue here if you wanted
    if ([[self networkQueue] requestsCount] == 0) {
        [self setNetworkQueue:nil]; 
    }

    //... Handle failure
    NSLog(@"Request failed");
}


- (void)queueFinished:(ASINetworkQueue *)queue
{
    // You could release the queue here if you wanted
    if ([[self networkQueue] requestsCount] == 0) {
        [self setNetworkQueue:nil]; 
    }
    NSLog(@"Queue finished");
}

@synthesize networkQueue;
@end