iphone - NSMutableURLRequest 和 NSURLConnection 无法在 GCDdispatch_async 中工作?

标签 iphone nsurlconnection grand-central-dispatch nsurlrequest nsmutableurlrequest

我在 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

谢谢!

最佳答案

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

If you don’t schedule the connection in a run loop or an operation queue before calling this method, the connection is scheduled in the current run loop in the default mode.

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

关于iphone - NSMutableURLRequest 和 NSURLConnection 无法在 GCDdispatch_async 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9527607/

相关文章:

iphone - 是否有任何 API 或示例代码可用于 iPhone 应用程序中的 Pinterest 集成?

ios - iOS Objective C 中的错误域=NSURLErrorDomain 代码=-1012 "(null)"

iphone - NSURLConnection 返回数据但我无法读取它

ios - 如何管理多个异步 NSURLConnection 请求

iphone - iOS : Best way to organise multithreading

iphone - 在 iPhone 模拟器中模拟电话中断

iphone - 具有自定义值 : The right way 的可重用 Objc 类

ios - 您的二进制文件未针对 iPhone 5 进行优化

arrays - 从异步调用修改数组不会快速修改数组

ios - 如何发送/返回值从 dispatch_sync(dispatch_get_main_queue(), {} 到另一个页面