20
20
@implementation NSURLSession (Swizzling)
21
21
22
22
+ (void )load {
23
-
23
+
24
24
Method oriMethod = class_getInstanceMethod ([NSURLSession class ], @selector (dataTaskWithRequest: ));
25
25
Method newMethod = class_getInstanceMethod ([NSURLSession class ], @selector (dataTaskWithRequest_swizzling: ));
26
26
method_exchangeImplementations (oriMethod, newMethod);
@@ -81,29 +81,38 @@ + (void)swizzling_TaskWillPerformHTTPRedirectionIntoDelegateClass:(Class)cls {
81
81
82
82
+ (void )swizzling_TaskDidSendBodyDataIntoDelegateClass : (Class )cls {
83
83
SEL selector = @selector (URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend: );
84
- // SEL swizzledSelector = @selector(URLSession_swizzling:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:);
85
- // Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
86
- //
87
- // struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
88
- // [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription];
89
-
84
+ // SEL swizzledSelector = @selector(URLSession_swizzling:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:);
85
+ // Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
86
+ //
87
+ // struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
88
+ // [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription];
89
+
90
90
NSError *error;
91
91
92
92
[cls aspect_hookSelector: selector
93
- withOptions: AspectPositionBefore
94
- usingBlock: ^(id <AspectInfo> aspectInfo,NSURLSession *session,NSURLSessionTask *task){
95
-
96
- [self addRequestModel: session task: task];
97
-
98
- }
99
- error: &error];
93
+ withOptions: AspectPositionBefore
94
+ usingBlock: ^(id <AspectInfo> aspectInfo,NSURLSession *session,NSURLSessionTask *task){
95
+
96
+ [self addRequestModel: session task: task];
97
+
98
+ }
99
+ error: &error];
100
+
100
101
}
101
102
+(void )addRequestModel : (NSURLSession *)session task : (NSURLSessionTask *)task {
102
103
103
104
NSURLRequest * req = task.originalRequest ;
104
- req.requestId = [[NSUUID UUID ] UUIDString ];
105
- req.startTime = @([[NSDate date ] timeIntervalSince1970 ]);
106
105
106
+ if ([[JxbHttpDatasource shareInstance ] arrRequestContainObject: req.requestId])
107
+ return ;
108
+
109
+ if (![self canHandle: req])
110
+ return ;
111
+
112
+ [self createModel: req statusCode: @" 100" ];
113
+
114
+ }
115
+ +(BOOL )canHandle : (NSURLRequest *)req {
107
116
BOOL canHandle = YES ;
108
117
if ([[JxbDebugTool shareInstance ] arrOnlyHosts ].count > 0 ) {
109
118
canHandle = NO ;
@@ -115,16 +124,20 @@ +(void)addRequestModel:(NSURLSession *)session task:(NSURLSessionTask *)task {
115
124
}
116
125
}
117
126
}
118
- if (!canHandle)
119
- return ;
127
+ return canHandle;
128
+ }
129
+ +(void )createModel : (NSURLRequest *)req statusCode : (NSString *)statusCode {
130
+
131
+ req.requestId = [[NSUUID UUID ] UUIDString ];
132
+ req.startTime = @([[NSDate date ] timeIntervalSince1970 ]);
120
133
121
134
JxbHttpModel* model = [[JxbHttpModel alloc ] init ];
122
135
model.requestId = req.requestId ;
123
136
model.url = req.URL ;
124
137
model.method = req.HTTPMethod ;
125
138
model.requestAllHTTPHeaderFields = req.allHTTPHeaderFields ;
126
139
model.startTime = [NSString stringWithFormat: @" %f s" ,req.startTime.doubleValue];
127
- model.statusCode = @" 100 " ;
140
+ model.statusCode = statusCode ;
128
141
if (req.HTTPBody ) {
129
142
NSData * data = req.HTTPBody ;
130
143
if ([[JxbDebugTool shareInstance ] isHttpRequestEncrypt ]) {
@@ -137,7 +150,6 @@ +(void)addRequestModel:(NSURLSession *)session task:(NSURLSessionTask *)task {
137
150
138
151
[[JxbHttpDatasource shareInstance ] addHttpRequset: model];
139
152
[[NSNotificationCenter defaultCenter ] postNotificationName: kNotifyKeyReloadHttp object: nil ];
140
-
141
153
}
142
154
+ (void )swizzling_TaskDidReceiveChallengeIntoDelegateClass : (Class )cls {
143
155
SEL selector = @selector (URLSession:task:didReceiveChallenge:completionHandler: );
@@ -159,11 +171,11 @@ + (void)swizzling_TaskNeedNewBodyStreamIntoDelegateClass:(Class)cls {
159
171
160
172
+ (void )swizzling_TaskDidCompleteWithErrorIntoDelegateClass : (Class )cls {
161
173
SEL selector = @selector (URLSession:task:didCompleteWithError: );
162
- // SEL swizzledSelector = @selector(URLSession_swizzling:task:didCompleteWithError:);
163
- // Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
164
- //
165
- // struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
166
- // [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription];
174
+ // SEL swizzledSelector = @selector(URLSession_swizzling:task:didCompleteWithError:);
175
+ // Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
176
+ //
177
+ // struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
178
+ // [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription];
167
179
168
180
NSError *error;
169
181
@@ -183,9 +195,9 @@ - (void)URLSession_swizzling:(NSURLSession *)session task:(NSURLSessionTask *)ta
183
195
}
184
196
185
197
- (void )URLSession_swizzling : (NSURLSession *)session task : (NSURLSessionTask *)task didSendBodyData : (int64_t )bytesSent totalBytesSent : (int64_t )totalBytesSent totalBytesExpectedToSend : (int64_t )totalBytesExpectedToSend {
186
-
187
198
188
- // [self URLSession_swizzling:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalBytesExpectedToSend];
199
+
200
+ // [self URLSession_swizzling:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalBytesExpectedToSend];
189
201
}
190
202
191
203
- (void )URLSession_swizzling : (NSURLSession *)session task : (NSURLSessionTask *)task didReceiveChallenge : (NSURLAuthenticationChallenge *)challenge completionHandler : (void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler {
@@ -197,34 +209,63 @@ - (void)URLSession_swizzling:(NSURLSession *)session task:(NSURLSessionTask *)ta
197
209
}
198
210
199
211
+(void )URLSession_swizzling : (NSURLSession *)session task : (NSURLSessionTask *)task didCompleteWithError : (nullable NSError *)error {
200
- // [self URLSession_swizzling:session task:task didCompleteWithError:error];
201
-
202
- NSURLRequest * req = task.originalRequest ;
203
- if (![[JxbHttpDatasource shareInstance ] arrRequestContainObject: req.requestId])
204
- return ;
212
+ // [self URLSession_swizzling:session task:task didCompleteWithError:error];
205
213
214
+ NSURLRequest * req = task.originalRequest ;
206
215
NSURLResponse * resp = task.response ;
207
-
208
- __block JxbHttpModel* model ;
209
- NSMutableArray *httpArray = [[[JxbHttpDatasource shareInstance ] httpArray ] mutableCopy ];
210
- [httpArray enumerateObjectsUsingBlock: ^(JxbHttpModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
216
+ NSHTTPURLResponse * httpResponse = ( NSHTTPURLResponse *)resp;
217
+ NSString *statusCode = [ NSString stringWithFormat: @" %d " ,( int )httpResponse.statusCode] ;
218
+
219
+ if ([[JxbHttpDatasource shareInstance ] arrRequestContainObject: req.requestId]) {
211
220
212
- if ([obj.requestId isEqualToString: req.requestId]){
213
- model = obj;
214
- *stop = YES ;
221
+ __block JxbHttpModel* model;
222
+ NSMutableArray *httpArray = [[[JxbHttpDatasource shareInstance ] httpArray ] mutableCopy ];
223
+ [httpArray enumerateObjectsUsingBlock: ^(JxbHttpModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
224
+
225
+ if ([obj.requestId isEqualToString: req.requestId]){
226
+ model = obj;
227
+ *stop = YES ;
228
+ }
229
+ }];
230
+
231
+ model.statusCode = statusCode;
232
+ model.responseData = task.responseDatas ;
233
+ model.responseAllHTTPHeaderFields = httpResponse.allHeaderFields ;
234
+ model.mineType = httpResponse.MIMEType ;
235
+ model.isImage = [resp.MIMEType rangeOfString: @" image" ].location != NSNotFound ;
236
+ model.totalDuration = [NSString stringWithFormat: @" %f s" ,[[NSDate date ] timeIntervalSince1970 ] - model.startTime.doubleValue];
237
+
238
+ [[NSNotificationCenter defaultCenter ] postNotificationName: kNotifyKeyReloadHttp object: model];
239
+ }
240
+ else if ([self canHandle: req]){
241
+
242
+ JxbHttpModel* model = [[JxbHttpModel alloc ] init ];
243
+ model.requestId = req.requestId ;
244
+ model.url = req.URL ;
245
+ model.method = req.HTTPMethod ;
246
+ model.requestAllHTTPHeaderFields = req.allHTTPHeaderFields ;
247
+ model.startTime = [NSString stringWithFormat: @" %f s" ,[[NSDate date ] timeIntervalSince1970 ]];
248
+ model.statusCode = statusCode;
249
+ if (req.HTTPBody ) {
250
+ NSData * data = req.HTTPBody ;
251
+ if ([[JxbDebugTool shareInstance ] isHttpRequestEncrypt ]) {
252
+ if ([[JxbDebugTool shareInstance ] delegate ] && [[JxbDebugTool shareInstance ].delegate respondsToSelector: @selector (decryptJson: )]) {
253
+ data = [[JxbDebugTool shareInstance ].delegate decryptJson: req.HTTPBody];
254
+ }
255
+ }
256
+ model.requestBody = [JxbHttpDatasource prettyJSONStringFromData: data error: nil ];
215
257
}
216
- }];
217
-
218
- NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *)resp;
219
- model.statusCode = [NSString stringWithFormat: @" %d " ,(int )httpResponse.statusCode];
220
- model.responseData = task.responseDatas ;
221
- model.responseAllHTTPHeaderFields = httpResponse.allHeaderFields ;
222
- model.mineType = httpResponse.MIMEType ;
223
- model.isImage = [resp.MIMEType rangeOfString: @" image" ].location != NSNotFound ;
224
- NSString *mimeType = resp.MIMEType ;
225
- model.totalDuration = [NSString stringWithFormat: @" %f s" ,[[NSDate date ] timeIntervalSince1970 ] - model.startTime.doubleValue];
226
-
227
- [[NSNotificationCenter defaultCenter ] postNotificationName: kNotifyKeyReloadHttp object: model];
258
+
259
+ model.responseData = task.responseDatas ;
260
+ model.responseAllHTTPHeaderFields = httpResponse.allHeaderFields ;
261
+ model.mineType = httpResponse.MIMEType ;
262
+ model.isImage = [resp.MIMEType rangeOfString: @" image" ].location != NSNotFound ;
263
+ model.totalDuration = [NSString stringWithFormat: @" %f s" ,[[NSDate date ] timeIntervalSince1970 ] - model.startTime.doubleValue];
264
+
265
+
266
+ [[JxbHttpDatasource shareInstance ] addHttpRequset: model];
267
+ [[NSNotificationCenter defaultCenter ] postNotificationName: kNotifyKeyReloadHttp object: nil ];
268
+ }
228
269
229
270
}
230
271
@@ -235,7 +276,7 @@ + (void)swizzling_selectors_data:(Class)cls {
235
276
[self swizzling_TaskDidReceiveDataIntoDelegateClass: cls];
236
277
[self swizzling_TaskDidBecomeDownloadTaskIntoDelegateClass: cls];
237
278
[self swizzling_TaskDidBecomeStreamTaskIntoDelegateClass: cls];
238
- // [self swizzling_TaskWillCacheResponseIntoDelegateClass:cls];
279
+ // [self swizzling_TaskWillCacheResponseIntoDelegateClass:cls];
239
280
}
240
281
241
282
+ (void )swizzling_TaskDidReceiveResponseIntoDelegateClass : (Class )cls {
@@ -251,7 +292,7 @@ + (void)swizzling_TaskDidReceiveDataIntoDelegateClass:(Class)cls {
251
292
SEL selector = @selector (URLSession:dataTask:didReceiveData: );
252
293
SEL swizzledSelector = @selector (URLSession_swizzling:dataTask:didReceiveData: );
253
294
Protocol *protocol = @protocol (NSURLSessionDataDelegate);
254
-
295
+
255
296
struct objc_method_description methodDescription = protocol_getMethodDescription (protocol, selector, NO , YES );
256
297
[self replaceImplementationOfSelector: selector withSelector: swizzledSelector forClass: cls withMethodDescription: methodDescription];
257
298
}
@@ -291,7 +332,7 @@ + (void)replaceImplementationOfSelector:(SEL)selector withSelector:(SEL)swizzled
291
332
Method newMethod = class_getInstanceMethod (cls, swizzledSelector);
292
333
method_exchangeImplementations (oldMethod, newMethod);
293
334
} else { // 没有实例方法的话,就不要添加
294
- // class_addMethod(cls, selector, implementation, methodDescription.types);
335
+ // class_addMethod(cls, selector, implementation, methodDescription.types);
295
336
}
296
337
}
297
338
@@ -312,6 +353,7 @@ - (void)URLSession_swizzling:(NSURLSession *)session dataTask:(NSURLSessionDataT
312
353
}
313
354
if ([dataTask.taskDataIdentify isEqualToString: NSStringFromClass ([self class ])])
314
355
[dataTask.responseDatas appendData: data];
356
+
315
357
[self URLSession_swizzling: session dataTask: dataTask didReceiveData: data];
316
358
}
317
359
0 commit comments