iOS Developer

NSURLProtocol使用

2017-09-20  本文已影响153人  毅个天亮

NSURLProtocol可以让你重新定义苹果的URL Loading System操作,通过实现一个NSURLProtocol子类,可以修改网络请求的URL(重定向),给请求添加header等。或者如果需要监测Webview发起的请求,那么使用NSURLProtocol也是一个很好的选择。

NSURLProtocol是一个抽象类,使用时必须以子类形式,并且需要进行注册。

[NSURLProtocol registerClass:[MyURLProtocol class]];

NSURLProtocol的文档中,对需要子类重写实现的方法单独划分了一个区域

/*======================================================================
  Begin responsibilities for protocol implementors

  The methods between this set of begin-end markers must be
  implemented in order to create a working protocol.
  ======================================================================*/

+ (BOOL)canInitWithRequest:(NSURLRequest *)request;

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request;

+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b;

- (void)startLoading;

- (void)stopLoading;

/*======================================================================
  End responsibilities for protocol implementors
  ======================================================================*/

每当URL Loading System收到一个加载URL的请求时,会试图从注册的NSURLProtocol中找出一个可以处理这个请求的。注册一个类的时候,会将这个类放在所有已注册类的前面,这个类会最先被询问是否可以处理请求。第一个返回YES的类赢得处理这个请求的机会,系统停止继续询问其他类,因此并非每个类都有机会被询问到。

每个NSURLProtocol子类通过重写下面的方法,告诉系统它是否能够处理这个请求:

// 这是一个抽象方法,子类必须提供实现
+ (BOOL)canInitWithRequest:(NSURLRequest *)request;

如果所有注册的NSURLProtocol都返回NO,那么URL Loading System会自己处理这个request,用系统默认的方式。

如果我们实现的子类返回了YES,则表示这个请求会由这个协议来处理,系统会通过另一个类方法要求我们返回一个标准的请求,我们可以在这个方法中对请求进行修改,如URL重定向、添加Header等:

// 这是一个抽象方法,子类必须提供实现
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    NSMutableURLRequest *req = [request mutableCopy];
    NSMutableDictionary *headers = req.allHTTPHeaderFields.mutableCopy;
    [headers setValue:@"value" forKey:@"key"];
    req.allHTTPHeaderFields = headers;
    req.URL = [NSURL URLWithString:@"http://www.google.com"];
    return req.copy;
}

什么是"标准请求"完全由开发者自己来定义,即可以对request进行任意修改,但是需要保证相同的request最终产生的标准请求是一样的。因为一个请求产生的标准请求会被用来查找URL缓存,检查的过程中用标准请求来和其他请求对比是否相同。

// 此方法抽象类提供了默认的实现,重写可以直接调用父类
+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b
{
    return [super requestIsCacheEquivalent:a toRequest:b];
}

如果两个请求都被同一个protocol处理,且这个协议认为两者是相等的,这两个请求会使用同一个缓存。

自定义协议(NSURLProtocol子类)处理请求时,需要自己负责从网络获取数据等工作,最后这些数据从我们的协议再返回给系统。
这个数据的返回是通过协议的一个id <NSURLProtocolClient> client属性,调用它的一系列协议方法,完成数据回传到系统。

由于协议处理请求需要自己负责发起网络请求获取数据,发起网路请求又会产生一个request,系统又会询问协议能否处理这个请求,为了跳出这个无限循环,可以为这个请求设置一个属性用来判断:

+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    ...
    if ([NSURLProtocol propertyForKey:URLProtocolHandledKey inRequest:request]) {
            return NO;
    }
    ...
}

- (void)startLoading {
    ...
    [NSURLProtocol setProperty:@YES forKey:@"URLProtocolHandledKey" inRequest:self.request.mutableCopy];
    ...
}

下面为一个简单的子类示例,这个子类将foo://xxx这样的URL重定向到https://www.google.com?search?q=xxx

redirect.gif
#import "MyURLProtocol.h"

static NSString * const URLProtocolHandledKey = @"URLProtocolHandledKey";

@interface MyURLProtocol () <NSURLSessionDataDelegate, NSURLConnectionDelegate>
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSURLSessionDataTask *task;
@end

@implementation MyURLProtocol

+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    if ([NSURLProtocol propertyForKey:URLProtocolHandledKey inRequest:request]) {
        return NO;
    }
    if ([request.URL.scheme isEqualToString:@"foo"]) {
        return YES;
    }
    return NO;
    
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    if ([request.URL.scheme isEqualToString:@"foo"]) {
        NSMutableURLRequest *req = request.mutableCopy;
        if (request.URL.path.length > 0) {
            /*
             Webview加载原始URL: foo://xxx的时候,会默认尝试加载一些URL对应的资源,如foo://iOS%20Developer/images/nav_logo285.png
             这里需要将这些加载的URL重定向到Google去,如https://www.google.com/images/nav_logo285.png
             */
            NSString *urlPath = [NSString stringWithFormat:@"https://www.google.com/%@", request.URL.path];
            req.URL = [NSURL URLWithString:urlPath];
            return req;
        }
        else {
            NSString *host = request.URL.host;
            host = [host stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            NSString *urlPath = [NSString stringWithFormat:@"https://www.google.com/search?q=%@",host];
            req.URL = [NSURL URLWithString:urlPath];
            return req;
        }
        
    }
    return request;
}

+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b
{
    BOOL rst = [super requestIsCacheEquivalent:a toRequest:b];
    return rst;
}

- (void)startLoading {
    NSMutableURLRequest *req = [[self request] mutableCopy];
    [NSURLProtocol setProperty:@YES forKey:URLProtocolHandledKey inRequest:req];
    self.task = [self.session dataTaskWithRequest:req];
    [self.task resume];
}

- (void)stopLoading {
    [self.task cancel];
}

#pragma mark - NSURLSessionTaskDelegate
- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
    completionHandler(NSURLSessionResponseAllow);
}


- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    [self.client URLProtocol:self didLoadData:data];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    if (error) {
        [self.client URLProtocol:self didFailWithError:error];
    } else {
        [self.client URLProtocolDidFinishLoading:self];
    }
}

#pragma mark - Lazy load
- (NSURLSession *)session {
    if (!_session) {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    }
    return _session;
}

@end

上文中的Demo:NSURLProtocolDemo

文章是在阅读raywenderlich上的相关教程后整理的,教程中也附带一个Demo工程(使用CoreData缓存请求数据)。

上一篇 下一篇

猜你喜欢

热点阅读