NSURLConnection委托后台线程的方法

时间:2012-04-20 15:47:47

标签: ios nsurlconnection selector grand-central-dispatch sudzc

EDIT2 - 重写了问题

我想在后台进行一些Web服务通信。我使用Sudzc作为HTTPRequests的处理程序,它的工作方式如下:

SudzcWS *service = [[SudzcWS alloc] init];
[service sendOrders:self withXML:@"my xml here" action:@selector(handleOrderSending:)];
[service release];

它向Web服务发送一些XML,并在指定的选择器中处理响应(在这一个中,布尔值):

- (void)handleOrderSending:(id)value
{ 
//some controls  
    if ([value boolValue] == YES)
    {
        //my stuff
    }
}

当我尝试在我的sendOrders:withXML:action:方法上使用Grand Central Dispatch时,我注意到没有调用选择器。我相信原因是 NSURLConnection委托消息被发送到创建连接的线程但是线程没有那么长时间,它在方法结束时结束,杀死任何消息到代表。

此致

EDIT1 [request send]方法:

- (void) send {
//dispatch_async(backgroundQueue, ^(void){
    // If we don't have a handler, create a default one
    if(handler == nil) {
        handler = [[SoapHandler alloc] init];
    }

    // Make sure the network is available
    if([SoapReachability connectedToNetwork] == NO) {
        NSError* error = [NSError errorWithDomain:@"SudzC" code:400 userInfo:[NSDictionary dictionaryWithObject:@"The network is not available" forKey:NSLocalizedDescriptionKey]];
        [self handleError: error];
    }

    // Make sure we can reach the host
    if([SoapReachability hostAvailable:url.host] == NO) {
        NSError* error = [NSError errorWithDomain:@"SudzC" code:410 userInfo:[NSDictionary dictionaryWithObject:@"The host is not available" forKey:NSLocalizedDescriptionKey]];
        [self handleError: error];
    }

    // Output the URL if logging is enabled
    if(logging) {
        NSLog(@"Loading: %@", url.absoluteString);
    }

    // Create the request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL: url];
    if(soapAction != nil) {
        [request addValue: soapAction forHTTPHeaderField: @"SOAPAction"];
    }
    if(postData != nil) {
        [request setHTTPMethod: @"POST"];
        [request addValue: @"text/xml; charset=utf-8" forHTTPHeaderField: @"Content-Type"];
        [request setHTTPBody: [postData dataUsingEncoding: NSUTF8StringEncoding]];

        if(self.logging) {
            NSLog(@"%@", postData);
        }
    }


    //dispatch_async(dispatch_get_main_queue(), ^(void){
        // Create the connection
        conn = [[NSURLConnection alloc] initWithRequest: request delegate: self];
        if(conn) {
                                        NSLog(@" POST DATA %@", receivedData);
            receivedData = [[NSMutableData data] retain];
                        NSLog(@" POST DATA %@", receivedData);
        } else {
            // We will want to call the onerror method selector here...
            if(self.handler != nil) {
                NSError* error = [NSError errorWithDomain:@"SoapRequest" code:404 userInfo: [NSDictionary dictionaryWithObjectsAndKeys: @"Could not create connection", NSLocalizedDescriptionKey,nil]];
                [self handleError: error];
            }
        }
    //});


    //finished = NO;

    //    while(!finished) {
    //        
    //        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    //        
    //    }

//});
}

注释掉的部分是我尝试过的各种各样的东西。最后一部分有效,但我不确定这是不是一个好方法。在类的NURLConnection委托方法中,会发生以下情况:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError* error;
if(self.logging == YES) {
    NSString* response = [[NSString alloc] initWithData: self.receivedData     encoding: NSUTF8StringEncoding];
    NSLog(@"%@", response);
    [response release];
}

CXMLDocument* doc = [[CXMLDocument alloc] initWithData: self.receivedData options: 0 error: &error];
if(doc == nil) {
    [self handleError:error];
    return;
}

id output = nil;
SoapFault* fault = [SoapFault faultWithXMLDocument: doc];

if([fault hasFault]) {
    if(self.action == nil) {
        [self handleFault: fault];
    } else {
        if(self.handler != nil && [self.handler respondsToSelector: self.action]) {

                [self.handler performSelector: self.action withObject: fault];


        } else {
            NSLog(@"SOAP Fault: %@", fault);
        }
    }
} else {
    CXMLNode* element = [[Soap getNode: [doc rootElement] withName: @"Body"] childAtIndex:0];
    if(deserializeTo == nil) {
        output = [Soap deserialize:element];
    } else {
        if([deserializeTo respondsToSelector: @selector(initWithNode:)]) {
            element = [element childAtIndex:0];
            output = [deserializeTo initWithNode: element];
        } else {
            NSString* value = [[[element childAtIndex:0] childAtIndex:0] stringValue];
            output = [Soap convert: value toType: deserializeTo];
        }
    }

    if(self.action == nil) { self.action = @selector(onload:); }
    if(self.handler != nil && [self.handler respondsToSelector: self.action]) {


            [self.handler performSelector: self.action withObject: output];


    } else if(self.defaultHandler != nil && [self.defaultHandler respondsToSelector:@selector(onload:)]) {
        [self.defaultHandler onload:output];
    }
}

[self.handler release];
[doc release];
[conn release];
conn = nil;
[self.receivedData release];
}

委托无法发送消息,因为-(void)send完成后该节点已经死亡。

2 个答案:

答案 0 :(得分:2)

sendOrders的方法定义表明它已经设计为以异步方式执行请求。您应该查看sendOrders: withXML: action:的实现,以了解是否属于这种情况。

如果没有使用GCD或SudzcWS的代码看到您的实现,很难说出现了什么问题。尽管有上述警告,但以下内容可能有用。

看起来您可能会在完成之前发布SudzcWS *service

以下内容:

SudzcWS *service = [[SudzcWS alloc] init];
dispatch_async(aQueue, ^{
    [sevice sendOrders:self withXML:xml action:@selector(handleOrderSending:)];
}
[service release];
除非SudzcWS保留自己,否则

可能会失败。您异步调度块,它将被放入队列,并继续执行该方法。 service被释放并在块执行之前或service等待来自网络服务器的响应时被取消分配。

除非另有说明,否则调用选择器将在调用它的同一线程上执行该选择器。做类似的事情:

SudzcWS *service = [[SudzcWS alloc] init];
dispatch_async(aQueue, ^{
    [sevice sendOrders:self withXML:xml action:@selector(handleOrderSending:)];
}


- (void)handleOrderSending:(id)value
{ 
    //some controls  
    //your stuff
    [service release];
}

应确保sendOrders:方法和handleOrderSending:在队列aQueue上执行,service在执行选择器之前不会释放。

这将要求您保留指向service的指针,以便handleOrderSending:可以释放它。您可能还想考虑简单地挂在单个SudzcWS实例上,而不是每次想要使用它时创建和释放一个,这应该可以使您的内存管理更加容易,并有助于保持对象图的紧密。

答案 1 :(得分:2)

我从SO NURLConnection questionoriginal这两个链接获得了帮助。

我的代码似乎没有风险,我将自行承担风险。感谢。

当然,仍然欢迎任何建议。

还要感谢Pingbat花时间尝试和帮助。