从connectionDidFinishLoading创建通知

时间:2013-07-21 11:51:00

标签: ios objective-c

为了发送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 


}

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

2 个答案:

答案 0 :(得分:0)

Connection did finish方法传递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 
    }    
}

答案 1 :(得分: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];
}

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