gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:03:57 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com