ios - 如何在ios中等待http请求的响应

标签 ios objective-c http

有人知道如何等待http请求的响应吗?在我的代码中,我正在对 url 执行 http 请求,然后我需要做的是检查 http 响应,以便决定不同的处理方式。我有这样的东西:

-(void)check{
[self fetchURL:@"http://something"];

if(response != nil || [response length] != 0){
      do something....
}
else{
      do something else....
}
}

-(void)fetchURL:(NSString *)urlWeb{
NSURL *url = [NSURL URLWithString:urlWeb];

NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[connection start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"INSIDE OF didReceiveResponse");
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"INSIDE OF didFailWithError");
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"INSIDE OF connectionDidFinishLoading");
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
NSLog(@"inside of didReceiveData");

response = [NSString stringWithUTF8String:[data bytes]];

NSLog(@"response: %@", response);
}

我一直在尝试我在这里看到的不同选项,但我无法停止代码的执行并等待答案......这意味着当我检查我的http请求的响应时,它总是显示为空或零引用... 有什么帮助如何弄清楚吗? 谢谢

最佳答案

您无法在“fetchUrl”调用后立即评估响应值,因为您的请求是异步的,并且您的代码会继续执行而不等待答案。您只会在其中一种委托(delegate)方法中收到响应值,因此您应该在此处检查结果。

如果你确实想发出同步请求,你可以使用 sendSynchronousRequest:returningResponse:error: 像这样

NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(data){
//use data
}
else{
//check error domain and code
}

( See the Apple NSURLConnection Reference )

但请记住,您的程序将卡在该调用上,直到收到响应或超时。

关于ios - 如何在ios中等待http请求的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17270802/

相关文章:

jquery - AngularJS 服务的返回值

ios - 为什么堆栈 View 会将等间距的水平按钮更改为框中等间距的按钮?

iphone - iPhone带小数点计算器教程

ios - 从Firebase动态链接进行的网址检测未返回iOS

java - 从浏览器上传多个文件的最佳方式

Java 使用 UTF-8 发送 http POST

ios - 我在 iOS 中收到 NSURLConnection 错误 -1100?

ios - UISearchBar 在 iOS 11 中的错误位置

ios - iPad 上的 UIDatePicker 布局问题

ios - `[AVCaptureSession canAddOutput:output]` 间歇性地返回 NO。我能找出原因吗?