//
// 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
网友评论