English 中文(简体)
NSURLConnection delegation methods on background thread
原标题:NSURLConnection delegate methods on background thread

EDIT2 - Rewrote the question

我想在此背景下进行一些网络服务交流。 我正在使用,Sudzc,作为HTTPRequests的手稿,并做如下工作:

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

该系统将一些XML发送到网络服务处,对(此处为一种,即“蓝色”)的答复由特定选择人处理:

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

当我试图在我的<密码>上使用大中分机时:与XML:action: 我注意到,选择人没有被传唤。 我认为,这样做的原因是: NSURLConnection 代表电文被发送到连接点的深处。 但是,read子没有住这么长的时间,在方法完结时,就结束了对代表的任何信息。

关于

EDIT1 [request send] method:

- (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];
}

该代表无法发送电文,因为电线在<代码>-(避免)send上消失。

最佳回答

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

我的守则似乎并不危险,我将冒着自己的风险使用。 感谢。

当然,任何建议都受到欢迎。

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

问题回答

<编码>编码>标准/编码”的方法定义表明,这一定义已经旨在以同步的方式执行请求。 您应研究<代码>端Orders: withXML: action:的执行情况,以发现情况。

如果没有看到你利用全球艾滋病与发展论坛或南方科学论坛的守则来执行,那么就很难说什么是错的。 尽管前面有点,但可以使用如下。

希望在《守则》完成之前发布<条码>。

如下:

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

could fail unless SudzcWS retains itself. You dispatch your block asynchronously, it gets put in a queue, and execution of the method continues. service is released and gets deallocated before the block executes or while service is waiting for a response from the webserver.

除非另有说明,否则,召集一名选择人将在同一条read线上执行。 做这样的事情:

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: methods and the handleOrderSending: are implementing on the queuecode>aQueue and that service is not release until it has implementing the selectedor.

这将要求你保持一个点,以<条码>服务。 因此,<代码>handleOrderSending:可予以公布。 你们可能还想简单地考虑hang向单一的南方首脑会议,而不是每当你想要利用它时就创造和释放一个例子,这应当使你的记忆管理更加容易,并有助于使你的标本紧缩。





相关问题
List Contents of Directory in a UITableView

I am trying to list the contents of Ringtones directory in a TableView, however, I am only getting the last file in the directory in ALL cells, instead of file per cell. This is my code: - (...

iPhone NSUserDefaults persistance difficulty

In my app i have a bunch of data i store in the NSUserdefaults. This information consists of an NSObject (Object1) with NSStrings and NSNumbers and also 2 instances of yet another object (Object2). ...

Writing a masked image to disk as a PNG file

Basically I m downloading images off of a webserver and then caching them to the disk, but before I do so I want to mask them. I m using the masking code everyone seems to point at which can be found ...

Resize UIImage with aspect ratio?

I m using this code to resize an image on the iPhone: CGRect screenRect = CGRectMake(0, 0, 320.0, 480.0); UIGraphicsBeginImageContext(screenRect.size); [value drawInRect:screenRect blendMode:...

Allowing interaction with a UIView under another UIView

Is there a simple way of allowing interaction with a button in a UIView that lies under another UIView - where there are no actual objects from the top UIView on top of the button? For instance, ...

热门标签