-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomURLProtocol.m
More file actions
102 lines (65 loc) · 2.63 KB
/
CustomURLProtocol.m
File metadata and controls
102 lines (65 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//
// CustomURLProtocol.m
// NSURLProtocolExample
//
// Created by lujb on 15/6/15.
// Copyright (c) 2015年 lujb. All rights reserved.
//
#import "CustomURLProtocol.h"
#import "MJExtension.h"
static NSString * const URLProtocolHandledKey = @"URLProtocolHandledKey";
@interface CustomURLProtocol ()<NSURLConnectionDelegate>
@property (nonatomic, strong) NSURLConnection *connection;
@end
@implementation CustomURLProtocol
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
//Handle HTTP and HTTPS requests.
NSString *scheme = [[request URL] scheme];
if ( ([scheme caseInsensitiveCompare:@"http"] == NSOrderedSame ||
[scheme caseInsensitiveCompare:@"https"] == NSOrderedSame))
{
//To prevent the circulation
if ([NSURLProtocol propertyForKey:URLProtocolHandledKey inRequest:request]) {
return NO;
}
return YES;
}
return NO;
}
+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
return request;
}
+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b
{
return [super requestIsCacheEquivalent:a toRequest:b];
}
- (void)startLoading
{
NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];
//To prevent the circulation
[NSURLProtocol setProperty:@YES forKey:URLProtocolHandledKey inRequest:mutableReqeust];
self.connection = [NSURLConnection connectionWithRequest:mutableReqeust delegate:self];
}
- (void)stopLoading
{
[self.connection cancel];
}
#pragma mark - NSURLConnectionDelegate
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];
NSString * body = [[ NSString alloc] initWithData:mutableReqeust.HTTPBody encoding:NSUTF8StringEncoding];
NSString *datastr = [[ NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Check network request. --- URL:%@, HTTPMethod:%@, body:%@, data:%@",mutableReqeust.URL,mutableReqeust.HTTPMethod,body,datastr);
[self.client URLProtocol:self didLoadData:data];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
[self.client URLProtocolDidFinishLoading:self];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[self.client URLProtocol:self didFailWithError:error];
}
@end