gpt4 book ai didi

objective-c - 等待 NSURLConnection

转载 作者:行者123 更新时间:2023-11-28 23:12:59 25 4
gpt4 key购买 nike

我有发送 HTTP POST 连接的代码。我希望该方法等到我从服务器收到响应才能继续。我这样做的原因是因为我正在将新代码(异步发布与旧的同步发布)集成到我们的应用程序中,并且我希望在整个应用程序中进行最小的更改。

旧方法如下:

-(NSData*) postData: (NSString*) strData;

应用程序会调用它并向它发送一个 strData 对象,然后它会锁定主线程,直到它得到返回值。这是低效的,但效果很好,但由于超时限制,我不得不更改它。

所以我的新方法(在这里发布完整的方法)如下:

-(NSData*) postData: (NSString*) strData
{
//start http request code
//postString is the STRING TO BE POSTED
NSString *postString;
//this is the string to send
postString = @"data=";
postString = [postString stringByAppendingString:strData];
NSURL *url = [NSURL URLWithString:@"MYSERVERURL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]];
//setting prarameters of the POST connection
[request setHTTPMethod:@"POST"];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:@"Content-Length"];
[request addValue:@"en-US" forHTTPHeaderField:@"Content-Language"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setTimeoutInterval:20]; //one second for testing purposes
NSLog(@"%@",postString);
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
//end http request code
return receivedData; //this is set by a delegate somewhere else in the code
}

它可以很好地发送代码,但当然(正如预期的那样),它接收代码的速度不够快,无法正确返回。

您建议我如何“停止”该方法以等待返回任何东西直到收到东西?我已经尝试设置一个 while 循环等待一个 BOOL ,当所有数据都被接收到时,该循环将被设置为 YES ,但该循环根本阻止了代码发送。我也试过把这个方法的内容丢到另一个方法中调用performSelectorInBackground,当然,这也没有用。我的想法已经用完了,非常感谢您的帮助。

最佳答案

在主线程上进行任何类型的同步通信都不是一个好主意,但如果此时您无法重新架构,请查看:

+[NSURLConnection sendSynchronousRequest:returningResponse:error:]

可以找到文档here .来自讨论:

A synchronous load is built on top of the asynchronous loading code made available by the class. The calling thread is blocked while the asynchronous loading system performs the URL load on a thread spawned specifically for this load request. No special threading or run loop configuration is necessary in the calling thread in order to perform a synchronous load.

但认真地看一下,异步执行请求并在请求完成时接收通知会涉及多少工作。用户的整体体验将会好得多。

关于objective-c - 等待 NSURLConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7572713/

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