如何检测 NSURLConnection 何时完成
我正在尝试使用 NSURLRequest
和 NSURLConnection
从 Web API 获取少量数据(大约 50 字节)。我很确定下面的代码是正确的,但是我如何实际获取接收到的数据并检测其何时全部下载?
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:req delegate:self];
I'm trying to use NSURLRequest
and NSURLConnection
to get a small bit of data (around 50 bytes) from a web API. I'm pretty sure the code below is right, but how do I actually get the received data and detect when its all downloaded?
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:req delegate:self];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过实现NSURLConnectionDelegate,您可以在
connection:didReceiveData:
方法中获取数据,并且当操作结束时将调用connectionDidFinishLoading:
方法。同时,如果操作过程中出现错误,connection:didFailWithError:
将会被调用。By implementing NSURLConnectionDelegate, you can get the data in
connection:didReceiveData:
method and theconnectionDidFinishLoading:
method will be called when the the operation is over. Meanwhile ,connection:didFailWithError:
will be called if there is some error during the operation.您将自己设置为代理人,连接将随时向您发送呼叫。
例子:
http://developer.apple.com/库/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
you set yourself as the delegate and the connection will send you calls as it goes.
example:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
您必须使用委托的方法,请阅读此处的文档: http://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSURLConnectionDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intf/NSURLConnectionDelegate
You have to use delegate's methods, read the documentation here: http://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSURLConnectionDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intf/NSURLConnectionDelegate