使用 Apple 推荐的 NSURL 委托方法 [英] Use Apple recommended NSURL delegate methods

查看:42
本文介绍了使用 Apple 推荐的 NSURL 委托方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我原来问题的答案使用以下代码.

NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:self.urlNameInput.text] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[NSURLConnection sendAsynchronousRequest:theRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *connection, NSData *data, NSError *error){...}];

我的原始代码不起作用,但如下所示.我的代码使用了 Apple Docs 中建议的一组委托方法( connection:didReceiveResponse:、connection:didReceiveData:、connection:didFailWithError: 和 connectionDidFinishLoading:).

My original code did not work, but was as follows. My code used a set of delegate methods ( connection:didReceiveResponse:, connection:didReceiveData:, connection:didFailWithError: and connectionDidFinishLoading:) suggested in Apple Docs.

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlNameInput.text] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
         if (theConnection) {
         receivedData = [NSMutableData data] ;
         } else {
         // Inform the user that the connection failed.
         NSLog(@"Their is an error with that URL.");
         };

委托方法是否与建议的代码兼容,如果是,我如何将它们集成到建议的代码中?

Are the delegate methods compatible with the suggested code, and if so, how can I integrate them into the suggested code?

推荐答案

您可以使用其中一种.

您问题中的第一段代码没有使用任何委托方法.相反,您在完成处理程序中执行所有操作.你要么得到数据,要么得到错误.您无需处理附加数据或处理重定向.

The first bit of code in your question does not use any delegate methods. Instead, you do everything in the completion handler. You either get the data or you get an error. You don't need to deal with appending data or processing redirects.

如果您需要更多控制,那么您必须使用旧形式以及正确的委托方法集.

If you need more control then you must use the older form along with the proper set of delegate methods.

完成处理程序版本要简单得多,除非您需要委托版本的灵活性,否则应该使用它.

The completion handler version is much simpler and should be used unless you need the flexibility of the delegate version.

这篇关于使用 Apple 推荐的 NSURL 委托方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆