有人知道如何等待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请求的响应时,它总是显示为空或没有参考...... 任何帮助如何搞清楚? 感谢
答案 0 :(得分:2)
在'fetchUrl'调用之后,您无法立即评估响应值,因为您的请求是异步的,并且您的代码继续执行而不等待答案。您只会在其中一个委托方法中收到响应值,因此您应该在那里检查结果。
如果你真的想要发出同步请求,可以使用sendSynchronousRequest:returningResponse:error:like this
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)
但请记住,您的程序将停留在此调用上,直到收到响应或超时。
答案 1 :(得分:0)
您是否尝试过检查connectionDidFinishLoading:
的问题?
这是在成功传输数据时调用的委托方法。在那个时间点之前,你不应该期待任何有意义的数据。
此外 - didReceiveData
应该为您提供同时收到的部分数据。显然你似乎没有处理它,也不只是存储它以供以后评估(见connectionDidFinishLoading
)
答案 2 :(得分:0)
你为什么不写这段代码:
if(response != nil || [response length] != 0){
do something....
}
else{
do something else....
}
在- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
方法中,除非您有完整的正确答案,否则它不会执行。
而且只是为了ado:正确获取数据的权利应该是:
- (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);
}