【问题标题】:NSMutableURLRequest and NSURLConnection can't work in GCD dispatch_async?NSMutableURLRequest 和 NSURLConnection 不能在 GCD dispatch_async 中工作?
【发布时间】:2012-03-02 03:33:50
【问题描述】:

我在dispatch_async 中提出了NSMutableURLRequest 请求,但它不起作用。但是,NSURLRequest 有效。代码:

dispatch_queue_t queue1 = dispatch_get_global_queue(0, 0);
dispatch_async(queue1, ^{

    NSMutableURLRequest* request  = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
    [request setHTTPMethod:@"GET"];
    NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate:nil];
    [connection start];//It doesn't work!

    //***
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
    NSURLResponse* theResponse = nil;
    NSError* theError = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:theRequest
                                         returningResponse:&theResponse 
                                                     error:&theError];
    //This works great!
});

NSMutableURLRequestNSURLRequest 有什么区别吗?或者,我错误地使用了NSURLConnection

谢谢!

【问题讨论】:

    标签: iphone nsurlconnection grand-central-dispatch nsurlrequest nsmutableurlrequest


    【解决方案1】:

    这并不是说您在一个地方而不是另一个地方使用了可变连接,而是您正在调用立即在当前线程上运行的同步请求方法,而不是需要运行循环来操作的异步方法。来自 -[NSURLConnection start] 的文档:

    如果您不安排 在调用此之前在运行循环或操作队列中连接 方法,连接被调度在当前运行循环中 默认模式。

    从后台线程的块中调用异步方法是多余的。您应该在主线程上调用异步方法(它立即返回并在后台安排其工作)或在异步调度块中调用同步方法。第二种方式,你不必处理所有的委托回调,但你放弃了对加载操作的一些控制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-23
      • 1970-01-01
      • 2012-12-17
      相关资源
      最近更新 更多