管理两个NSURLConnection

时间:2011-09-16 21:58:17

标签: iphone ios networking

我想从两个不同的kml文件中做两个异步请求,所以我先设置两个请求:

NSString *server1URL = [NSString stringWithFormat:...];
NSMutableURLRequest *firstRequest =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:server1URL]];
[firstRequest setHTTPMethod:@"GET"];
NSURLConnection *AConnection = [NSURLConnection connectionWithRequest:firstRequest delegate:self];

NSString *server2URL = [NSString stringWithFormat:...];
NSMutableURLRequest *secondRequest =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:server2URL]];
[secondRequest setHTTPMethod:@"GET"];
NSURLConnection *BConnection = [NSURLConnection connectionWithRequest:secondRequest delegate:self];

然后我初始化NSMutableData我将使用:

AResponseData = [[NSMutableData alloc] init];
BResponseData = [[NSMutableData alloc] init];

然后,我提到this帖子并做了这个:

connectionToInfoMapping = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionaryAddValue(connectionToInfoMapping, AConnection, [NSMutableDictionary dictionaryWithObject:AResponseData forKey:@"receivedData"]);
CFDictionaryAddValue(connectionToInfoMapping, BConnection, [NSMutableDictionary dictionaryWithObject:BResponseData forKey:@"receivedData"]);

好的,那就是代表:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    const NSMutableDictionary *connectionInfo = CFDictionaryGetValue(connectionToInfoMapping, connection);
    [[connectionInfo objectForKey:@"receivedData"] appendData:data];
}

因此,我可以将数据附加到与连接匹配的正确NSMutableData。

现在在- (void)connectionDidFinishLoading:(NSURLConnection *)connection,我想“如果A完成,请执行此操作,如果B完成,请执行此操作”,我的问题是,我该怎么做?

3 个答案:

答案 0 :(得分:2)

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    if( [connection isEqual: AConnection] ){
        // do connection A stuff
    }
    else if( [connection isEqual: BConnection] ){
        // do connection B stuff
    }  
}

答案 1 :(得分:0)

将GCD与sendSynchronousRequest:请求一起使用,它们将在后台运行。

示例:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(queue, ^{
    NSURLRequest *request = [NSURLRequest requestWithURL:url1];
    NSURLResponse *response;
    NSError *error;
    NSData *data1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    // do something with the data
});

dispatch_async(queue, ^{
    NSURLRequest *request = [NSURLRequest requestWithURL:url2];
    NSURLResponse *response;
    NSError *error;
    NSData *data2 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    // do something with the data
});

答案 2 :(得分:-1)

如何为每个连接分配标签,并通过connectionDidFinishLoading中的if / else或开关检查标签?