//
// 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
自定义 NSURLProtocol Demo
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 开发iOS应用的过程中,很多情景都要调用相机,大多数初学开发者都是采用的苹果提供的系统相机的方法。 头文件要遵守协...
- 桃花近日随流水,洞在清溪何处边!<保母虫> 最近太忙了, 抽个时间和大家分享一下一个小的练习,自定义 tabbar...