使用 NSURLConnection 的 delegate 处理 http 通信

在苹果 Foundation 库里面,提供了一个原生的 HTTP 处理类,那就是NSURLConnection。本文记录了使用这个库的最基本的支持,阅读了苹果官方文档之后的一些笔记。

本文地址:https://segmentfault.com/a/1190000006749099

前言

虽然说是NSURLConnection,但是实质上最核心的处理都在它的两个 delegate 中完成。其中NSURLConnectionDelegate是用来向远端发出请求到密码验证(HTTP Basic Authentication)这一阶段的处理,是一个很老资格的 delegate,分别在iOS 5.0+, OS X 10.7+, watchOS 2.0+使用。
  但是在最新的版本中(2015年之后),取消了(deprecated)相当数量的方法,导致开发方式要变化。以下就说明如何使用保留了的方法来进行开发。
  而NURLConnectionDataDelegate则是用来处理完成了认证之后,处理普通数据的 delegate。兼容版本和NSURLConnectionDelegate不同的是,直到OS X 10.8+才引入。
  下面基本上按照事先顺序来说明各个方法的使用方式。

《使用 NSURLConnection 的 delegate 处理 http 通信》

NSURLConnectionDelegate

响应用户密码请求

- (void)connection:(NSURLConnection *)connection
willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

在这个方法中,需要调用以下方法之一(来自于NSURLAuthenticationChallengeSender):

方法一:进行 basic 认证

调用[delegate sender]- useCrendencial:forAuthenticationChallenge:方法,如:

- (void)connection:(NSURLConnection *)connection
willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSURLCredencial *credencial = 
        [[NSURLCredencial alloc] initWithUser:@"admin"
                                     password:@"admin"
                                  persistence:NSURLcredencialPersistenceForSession];
    [[challenge sender] useCredencial:credencial
           forAuthenticationChallenge:challenge];

    return;
}

方法二:尝试跳过认证

使用- continueWithoutCredencialForAuthenticationChallenge:

方法三:放弃认证

- cancelAuthenticationChallenge:

方法四:尝试默认配置

- performDefaultHandlingForAuthenticationChallenge:

方法五:(po主表示不明)

- rejectProtectionSpaceAndContinueWithChallenge:

是否使用自动的 credential storage?

- (BOOL) connectionShouldUseCredentialStorage:(NSURLConnection *)connection;

默认是返回YES

错误处理

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error;

《使用 NSURLConnection 的 delegate 处理 http 通信》

NSURLConnectionDataDelegate

完成数据 header 的接收

- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response;

大多数情况下,此时可以做数据接收完毕时的处理了。这里有两个参考,建议阅读:iPhone开发中如何异步调用web service,以及IOS如何根据URL下载内容
  文中提及,当服务器接收到足够对象来创建NSURLResponse对象时,就会调用上面的方法。

中间数据的接收

- (void)connection:(NSURLConnection *)connection
    didReceiveData:(NSData *data)

数据接收完成

- (void)connectionDidFinishLoading:(NSURLConnection  *)connection

上述三个 delegate 方法在正常情况下就是依顺序调用的。

    原文作者:amc
    原文地址: https://segmentfault.com/a/1190000006749099
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞