objective-c - 等待 NSURLConnection

标签 objective-c ios nsurlconnection

我有发送 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/

相关文章:

ios - AFHTTPRequestOperation 超时

IOS Swift - 模态视图错误

c++ - Cocos2dx 如何在没有 Schedule Selector 的情况下每 5 秒调用一个函数?

ios - 什么是 diff b/w 同步和异步请求,如何以编程方式检查此操作

iphone - 停止后台线程的CFRunLoop

ios - 仅导入已更新的 XML

objective-c - [NSLocale PreferredLanguages] 和 [[NSUserDefaults standardUserDefaults] objectForKey : @"AppleLanguages"]? 之间有什么区别

html - 尝试从 html 中提取表数据

ios - swift: 将多个 <key, value> 对象添加到 NSDictionary

iOS/Obj-C - 在没有计时器的情况下触发本地通知?