后台线程上的NSURLConnection委托方法 [英] NSURLConnection delegate methods on background thread

查看:95
本文介绍了后台线程上的NSURLConnection委托方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

EDIT2-重写了问题

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

I want to do some web service communication in the background. I am using Sudzc as the handler of HTTPRequests and it works like this:

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

它将一些XML发送到Web服务,并在指定的选择器中处理响应(在本例中为布尔值):

It sends some XML to the webservice, and the response (in this one, a Boolean) is handled in the selector specified:

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

当我尝试在我的sendOrders:withXML:action:方法上使用Grand Central Dispatch时,我注意到未调用选择器.而且我相信原因是 NSURLConnection委托消息发送到了创建连接的线程,但是该线程的寿命并不长,它在方法完成时终止,从而杀死了所有要发送的消息.代表.

When I tried to use Grand Central Dispatch on my sendOrders:withXML:action: method, I noticed that the selector is not called. And I believe the reason for that is that NSURLConnection delegate messages are sent to the thread of which the connection is created But the thread does not live that long, it ends when the method finishes, killing any messages to the delegate.

致谢

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委托方法中,将发生以下情况:

The parts that are commented out are the various things I tried. The last part worked but I'M not sure if that's a good way. In the NURLConnection delegate method of the class, here is what happens:

- (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完成后该委托的线程死亡.

The delegate is unable to send messages because the thread it is dies when -(void)send finishes.

推荐答案

这两个链接都对我有所帮助原始一个.

I've had help from both these links SO NURLConnection question and the original one.

它对我的代码来说似乎没有风险,我将自行承担风险.谢谢.

It does not seem risky for my code and I will use it at my own risk. Thanks.

当然仍然欢迎任何建议.

Any recommendations are still welcome of course.

感谢Pingbat花时间尝试和帮助.

Additional thanks to Pingbat for taking the time to try and help.

这篇关于后台线程上的NSURLConnection委托方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆