GCD与NSURLConnection [英] GCD with NSURLConnection

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

问题描述

我正在使用 GCD 以异步方式发送 HTTP 请求。以下代码不起作用:

  dispatch_async(connectionQueue,^ {
NSMutableURLRequest * request = [[ NSMutableURLRequest alloc] init];

[请求setURL:[NSURL URLWithString:[NSString stringWithFormat:someURL]]];


NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start]; // not working
});

以上代码根本不起作用。我没有在NSURLConnectionDelegate的方法中回复任何问题。



但是当我尝试以下代码时,一切正常,我得到了适当的回调

  NSMutableURLRequest * request = [[NSMutableURLRequest alloc] init]; 

[请求setURL:[NSURL URLWithString:[NSString stringWithFormat:someURL]]];

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

dispatch_async(connectionQueue,^ {

[连接开始]; //工作正常。但为什么????
});

有人可以解释阻止/ GCD这种奇怪的行为吗?

解决方案

在代码示例的第一部分中尝试此操作 -

  dispatch_async(dispatch_get_main_queue(),^(void){
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}

如果你把连接放在后台队列中,它会在队列完成后被推开,因此你没有得到你的委托回调。连接可以在主队列中,所以它保持在主运行循环中以进行回调。或者,你可以创建自己的runloop,按照别人的建议为你处理你的后台操作。 / p>

I am using GCD to send HTTP request asynchronously. Here is the code that doesn't work:

dispatch_async(connectionQueue, ^{
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

        [request setURL:[NSURL URLWithString:[NSString stringWithFormat:someURL]]];


        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        [connection start];//Not working
    }); 

the above code is not working at all. I am not getting any call back in NSURLConnectionDelegate's methods.

But when i tried the following code, everything worked fine and i got proper callbacks

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

[request setURL:[NSURL URLWithString:[NSString stringWithFormat:someURL]]];

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

dispatch_async(connectionQueue, ^{

    [connection start]; // working fine. But WHY ????
});

Can some one please explain this weird behavior of block/GCD?

解决方案

Try this in the first part of your code sample-

dispatch_async(dispatch_get_main_queue(), ^(void){
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
}

If you put the connection in a background queue, it gets shoved away after the queue is complete, and thus you don't get your delegate callbacks. The connection can be in the main queue so it stays in the main run loop for callbacks to occur. Or, you can create your own runloop that handles your background operation for you as suggested by others.

这篇关于GCD与NSURLConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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