2

有人知道如何等待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 请求的响应时,它总是显示为空或为零参考...任何帮助如何弄清楚?谢谢

4

3 回答 3

2

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

如果你真的想发出一个同步请求,你可以使用 sendSynchronousRequest:returningResponse:error: 像这样

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

请参阅 Apple NSURLConnection 参考

但请记住,您的程序将一直停留在此调用上,直到它收到响应或超时。

于 2013-06-24T09:19:58.653 回答
0

您是否尝试检查响应connectionDidFinishLoading:

这就是数据传输成功时调用的委托方法。在该时间点之前,您不应期待任何有意义的数据。

此外 -didReceiveData应该为您提供同时收到的部分数据。显然您似乎没有处理它,也没有将其存储以供以后评估(witin connectionDidFinishLoading

于 2013-06-24T08:22:35.150 回答
0

你为什么不写这段代码:

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;方法中,除非您有完整的正确响应,否则它不会执行。

顺便说一句:正确获取数据的正确方法应该是:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [_responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSString *string = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
    if (string)
        NSLog(@"string = %@", string);
}
于 2013-06-24T09:28:21.013 回答