使用NSURLConnection处理响应

时间:2014-09-04 13:30:43

标签: ios nsurlconnection nsurlconnectiondelegate nsmutabledata

我创建了一个NSURLConnections数组,因为我正在运行for循环并创建多个NSURLConnections。

这是我的代码

for(int i = 0; i <count; i++)
{

 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:finalJson options:NSJSONWritingPrettyPrinted error:&error];
            if (!jsonData) {
                NSLog(@"Error creating JSON object: %@", [error localizedDescription]);
            }

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"httpLink"]];


            [request setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
            [request setValue:APIKEY forHTTPHeaderField:@"X_API_KEY"];

            [request setHTTPMethod:@"POST"];
            [request setHTTPBody:jsonData];

            m_dataPush = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];

            [m_dataPushArray addObject:m_dataPush];

            [m_dataPush start];


}

现在这是一个异步任务,代理函数将被调用如下,我知道如何处理一个请求,如下所示

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

    if(connection == m_dataPush || connection == m_dataPull)
    {
        NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
        m_responseCode = [httpResponse statusCode];//Get status code for response

        m_ResponseData = [[NSMutableData alloc] init];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared


    if(connection == m_dataPush || connection == m_dataPull)
    {
        [m_ResponseData appendData:data];
    }
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now


    if(connection == m_dataPush || connection == m_dataPull )
    {
        NSDictionary *response = [NSJSONSerialization JSONObjectWithData: m_ResponseData options: 0 error: &e];  //I am using sbjson to parse

    }   
}

但是我不知道如何处理这个委托方法中的NSURLConnections数组

2 个答案:

答案 0 :(得分:3)

它就像一个,除了代表需要为所有人保持状态。在最小委托代码中,这意味着只收集响应数据。为了跟踪哪个是哪个,你需要一些独特的东西(大多数时候他们的请求,这是唯一的作为URL的代理)。由于您的请求很难区分,因此更安全的密钥是连接的指针(作为字符串)......

声明连接字典:

@property(strong, nonatomic) NSMutableDictionary *dictionary;

创建连接并将其保存在字典中:

- (NSURLConnection *)connectionForRequest:(NSURLRequest *)request {
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    NSString *key = [NSString stringWithFormat:@"%p", connection];

    // create response data for the connection and save it in the dictionary
    self.dictionary[key] = [NSMutableData data];
    return  connection;
}

在需要时查找并返回其可变数据:

- (NSMutableData *)dataForConnection:(NSURLConnection *)connection {

    NSString *key = [NSString stringWithFormat:@"%p", connection];
    return self.dictionary[key];
}

完成后删除它:

- (void)removeConnection:(NSURLConnection *)connection {

    NSString *key = [NSString stringWithFormat:@"%p", connection];
    return [self.dictionary removeObjectForKey:key];
}

现在你的循环看起来像这样:

for(int i = 0; i <count; i++) {

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:finalJson options:NSJSONWritingPrettyPrinted error:&error];
    if (!jsonData) {
        NSLog(@"Error creating JSON object: %@", [error localizedDescription]);
    }

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"httpLink"]];

    // setup the request as you do in your code
    NSURLConnection *connection = [self connectionForRequest:request];
    [connection start];
}

委托方法如下所示:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    if ([httpResponse statusCode] >= 400) {
        NSLog(@"error");
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared

    NSMutableData *responseData = [self dataForConnection:connection];
    [responseData appendData:data];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSError *e;
    NSMutableData *responseData = [self dataForConnection:connection];
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options: 0 error: &e];

    [self removeConnection:connection];

    // do whatever you do with result
}

这可以作为创建连接和作为委托的通用模式。您可以使用以下方法概括创建:

答案 1 :(得分:0)

您可以使用一些方法: 1)通过添加一个属性为id的子类NSURLConnection(类似于UIView具有标记属性),因此在循环中设置带有一些int的标记。 2)使用+(void)sendAsynchronousRequest:(NSURLRequest *)请求队列:(NSOperationQueue )队列completionHandler:(void(^)(NSURLResponse ,NSData *,NSError *))处理程序

在案例2中,在块内部,您可以单独处理每个连接(如果您需要以不同的方式处理每个连接,则此批准无效。 3)在我看来,这是最好的方式 - &gt;创建NSMutableArray并添加与阵列的连接。在回调中,您可以询问

if(connection isEqual:myConnections[0]){
    // Handle it
}

if(connection isEqual:myConnections[1]){
    // Handle it and so on
}

当每个人需要以不同的方式处理时,第三种方法是好的