自定义 NSURLProtocol Demo

    //
    //  SunVideoURLProtocol.h
    //  SunVideoURLProtocol
    //
    //  Created by sunbohong on 16/6/27.
    //
    //
    
    #import <Foundation/Foundation.h>
    
    @interface SunVideoURLProtocol : NSURLProtocol
    
    @end


    //
    //  SunVideoURLProtocol.m
    //  SunVideoURLProtocol
    //
    //  Created by sunbohong on 16/6/27.
    //
    //
    
    #import "SunVideoURLProtocol.h"
    
    static NSString *const hasInitKey = @"SunVideoURLProtocolKey";
    
    @interface SunVideoURLProtocol ()
    
    @property (nonatomic, strong) NSMutableData *responseData;
    @property (nonatomic, strong) NSURLConnection *connection;
    
    @end
    
    @implementation SunVideoURLProtocol
    
    + (void)load {
        [NSURLProtocol registerClass:[SunVideoURLProtocol class]];
    }
    
    + (BOOL)canInitWithRequest:(NSURLRequest *)request {
        if ([NSURLProtocol propertyForKey:hasInitKey inRequest:request]) {
            return NO;
        }
        //可以根据项目修改此处的逻辑
        if ([request.URL.absoluteString rangeOfString:@"mp4"].length > 0) {
            return YES;
        } else{
            return NO;
        }
    }
    
    + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
        NSMutableURLRequest *mutableReqeust = [request mutableCopy];
        //修改header
        [mutableReqeust setValue:<#(nullable NSString *)#> forHTTPHeaderField:@"referer"];
        return mutableReqeust;
    }
    
    - (void)startLoading {
        NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];
        //防止递归调用
        [NSURLProtocol setProperty:@YES forKey:hasInitKey inRequest:mutableReqeust];
        self.connection = [NSURLConnection connectionWithRequest:mutableReqeust delegate:self];
    }
    
    - (void)stopLoading {
        [self.connection cancel];
    }
    
    #pragma mark- NSURLConnectionDelegate
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
        [self.client URLProtocol:self didFailWithError:error];
    }
    
    #pragma mark - NSURLConnectionDataDelegate
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
        self.responseData = [[NSMutableData alloc] init];
        [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        [self.responseData appendData:data];
        [self.client URLProtocol:self didLoadData:data];
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        [self.client URLProtocolDidFinishLoading:self];
        NSLog(@"%@", [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding]);
    }
    
    @end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容