0

为了发送 HTTP 请求,我使用 NSURLConnection 如下:

NSURLConnection *connection = [[NSURLConnection alloc]
                               initWithRequest:request
                               delegate:self
                               startImmediately:YES];

在 connectionDidFinishLoading 结束时,我需要发布不同的通知,具体取决于刚刚完成的 HTTP 请求。但是,在 connectionDidFinishLoading 内部,我对发送的请求类型没有明确的逻辑标识符:

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

// here i want to post various notifications, depending on the HTTP request that was completed 


}

这里最好的解决方案是什么?谢谢!

4

2 回答 2

0

Connection 确实完成方法传递了 NSURLConnection 对象,该对象具有请求和 url:

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"currentRequest: %@", connection.currentRequest);
    NSLog(@"originalRequest: %@", connection.originalRequest);

    // here do a if statement that compares url
    if ([connection.currentRequest.URL.absoluteString isEqualToString:@"http://google.co.uk"]) {
        NSLog(@"Equal to google");
        // post notification 
    }    
}
于 2013-07-21T12:21:42.690 回答
0

您可以使用MKNetworkKit 之类的框架。在这个框架中,你可以这样写:

- (void) sendRequest: (NSString*) aRequestPath
          httpMethod: (NSString*) aHttpMethod
         paramsBlock: (SMFillParametersForRequestBlock) aParamsBlock
        successBlock: (SMSaveRequestResultBlock) aSuccessBlock
          errorBlock: (SMErrorRequestResultBlock) aErrorBlock
            userInfo: (id) anUserInfo
{

    MKNetworkEngine* network_engine= [[MKNetworkEngine alloc] initWithHostName: MuseumsHostName];

    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];

    if (aParamsBlock)
    {
        aParamsBlock(params);
    }

    MKNetworkOperation* operation = [network_engine operationWithPath: aRequestPath
                                                               params: params
                                                           httpMethod: aHttpMethod
                                                                  ssl: NO];
    [operation onCompletion: ^(MKNetworkOperation* completedOperation){

        // parse response of current request:
        aSuccessBlock(completedOperation, anUserInfo, ...); 

    } onError: ^(NSError *error){

       // error handler: call block

    }];

    [network_engine enqueueOperation: operation];
}

相信我,这是最好的解决方案

于 2013-07-21T13:22:07.347 回答