我对从Web服务下载数据有疑问。一种方法是在下面提到的单行中下载它。
NSString *returnString = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:urlrequest returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];
获得它的另一种方法是通过 connectionDidFinishLoading
[..]
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:urlrequest delegate:self];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest: urlrequest returningResponse: &response error: nil];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(@"theConnection is NULL");
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"ERROR with theConenction");
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length: [webData length] encoding:NSUTF8StringEncoding];
}
这两者有什么区别吗?当我使用单独的类来解析响应时,不会调用NSURLConnection委托方法。
答案 0 :(得分:4)
你正在使用sendSynchronousRequest:returningResponse:error:,它不会调用任何委托方法,因为它不需要:当你调用它时,主线程会停止,直到请求完成并得到响应。
如果要发出异步请求,请使用connectionWithRequest:delegate:。我建议总是进行异步响应,因为同步请求会阻塞主线程,并且您的UI在此期间无法响应。动画将被中断。滚动变得生涩。如果你想使用同步请求,你应该在后台线程中进行。
答案 1 :(得分:1)
-sendSynchronousRequest:returningResponse:error:方法阻塞主线程(当然它在主线程上运行时,因为它可以从任何其他线程运行此方法,但我相信不推荐这样做。)
使用委托的方法是异步的,方法将触发,结果将(在将来的某个时候)在委托方法中返回。这样可以为用户提供更流畅的体验,因为主线程不会被阻止。
编辑个人由于上述原因,我几乎不会使用 -sendSynchronousRequest:returningResponse:error:方法。大多数时候,当我需要快速构建某些东西时,我会使用这种方法,例如概念验证。我想可以使用该方法进行小型下载,但如果发生超时(因为某些原因服务器已关闭),整个用户界面将被阻止(我相信)2分钟,这对最终用户来说非常烦人。
答案 2 :(得分:0)
Apple示例应用程序中提供了一个很好的演示来澄清您的疑问。您可以参考Apple's sample app以更好地理解异步请求并在单独的类中解析数据。