FLEX除了支持查看UI,內(nèi)存之外,還能看網(wǎng)絡(luò)抓包,下邊探究其底層的實(shí)現(xiàn):
load/setEnabled
要想抓包,就需要對(duì)一些代理函數(shù)進(jìn)行hook,主要邏輯在FLEXNetworkObserver這個(gè)類里邊。首先既然是hook,先找到其load函數(shù)實(shí)現(xiàn)如下:
+ (void)load
{
dispatch_async(dispatch_get_main_queue(), ^{
if ([self isEnabled]) {
[self injectIntoAllNSURLConnectionDelegateClasses];
}
});
}
這里的[self isEnabled]
是一個(gè)網(wǎng)絡(luò)抓包的開關(guān),用userdault
存在本地,在+[FLEXNetworkObserver setEnabled:]
的代碼如下:
+ (void)setEnabled:(BOOL)enabled
{
BOOL previouslyEnabled = [self isEnabled];
[[NSUserDefaults standardUserDefaults] setBool:enabled forKey:kFLEXNetworkObserverEnabledDefaultsKey];
if (enabled) {
[self injectIntoAllNSURLConnectionDelegateClasses];
}
if (previouslyEnabled != enabled) {
[[NSNotificationCenter defaultCenter] postNotificationName:kFLEXNetworkObserverEnabledStateChangedNotification object:self];
}
}
injectIntoAllNSURLConnectionDelegateClasses
上面兩個(gè)方法都調(diào)用了+[FLEXNetworkObserver injectIntoAllNSURLConnectionDelegateClasses]
方法,這個(gè)方法實(shí)現(xiàn)如下:
+ (void)injectIntoAllNSURLConnectionDelegateClasses
{
1.
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
2.
const SEL selectors[] = {
@selector(connectionDidFinishLoading:),
@selector(connection:willSendRequest:redirectResponse:),
@selector(connection:didReceiveResponse:),
@selector(connection:didReceiveData:),
@selector(connection:didFailWithError:),
@selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:),
@selector(URLSession:dataTask:didReceiveData:),
@selector(URLSession:dataTask:didReceiveResponse:completionHandler:),
@selector(URLSession:task:didCompleteWithError:),
@selector(URLSession:dataTask:didBecomeDownloadTask:delegate:),
@selector(URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:),
@selector(URLSession:downloadTask:didFinishDownloadingToURL:)
};
const int numSelectors = sizeof(selectors) / sizeof(SEL);
3.
Class *classes = NULL;
int numClasses = objc_getClassList(NULL, 0);
if (numClasses > 0) {
classes = (__unsafe_unretained Class *)malloc(sizeof(Class) * numClasses);
numClasses = objc_getClassList(classes, numClasses);
for (NSInteger classIndex = 0; classIndex < numClasses; ++classIndex) {
Class class = classes[classIndex];
if (class == [FLEXNetworkObserver class]) {
continue;
}
4.
unsigned int methodCount = 0;
Method *methods = class_copyMethodList(class, &methodCount);
5.
BOOL matchingSelectorFound = NO;
for (unsigned int methodIndex = 0; methodIndex < methodCount; methodIndex++) {
for (int selectorIndex = 0; selectorIndex < numSelectors; ++selectorIndex) {
if (method_getName(methods[methodIndex]) == selectors[selectorIndex]) {
[self injectIntoDelegateClass:class];
matchingSelectorFound = YES;
break;
}
}
if (matchingSelectorFound) {
break;
}
}
free(methods);
}
free(classes);
}
6.
[self injectIntoNSURLConnectionCancel];
[self injectIntoNSURLSessionTaskResume];
[self injectIntoNSURLConnectionAsynchronousClassMethod];
[self injectIntoNSURLConnectionSynchronousClassMethod];
[self injectIntoNSURLSessionAsyncDataAndDownloadTaskMethods];
[self injectIntoNSURLSessionAsyncUploadTaskMethods];
});
}
- 雖然有兩個(gè)方法調(diào)用這里,但是還是要確保swizzle的代碼只執(zhí)行一次
- 需要swizzle的方法清單,基本都是代理方法
- 獲取所有類,其實(shí)就是蘋果在
objc_getClassList
說明的時(shí)候就推薦使用這種方法來獲取 - 獲取類中的所有方法列表,這里不使用
class_getInstanceMethod()
是因?yàn)椴幌胗|發(fā)類的+initialize
方法 - 如果方法實(shí)現(xiàn)了任何swizzle的方法中的一個(gè)方法,就進(jìn)行hook
- hook其它類的一些方法(比如URLSession,URLSessionTask)
對(duì)于6中的hook就不展開講了,基本上是一些常規(guī)swizzle的操作
對(duì)于5,+[FLEXNetworkObserver injectIntoDelegateClass:]
的實(shí)現(xiàn)如下:
+ (void)injectIntoDelegateClass:(Class)cls
{
[self injectWillSendRequestIntoDelegateClass:cls];
[self injectDidReceiveDataIntoDelegateClass:cls];
[self injectDidReceiveResponseIntoDelegateClass:cls];
[self injectDidFinishLoadingIntoDelegateClass:cls];
[self injectDidFailWithErrorIntoDelegateClass:cls];
[self injectTaskWillPerformHTTPRedirectionIntoDelegateClass:cls];
[self injectTaskDidReceiveDataIntoDelegateClass:cls];
[self injectTaskDidReceiveResponseIntoDelegateClass:cls];
[self injectTaskDidCompleteWithErrorIntoDelegateClass:cls];
[self injectRespondsToSelectorIntoDelegateClass:cls];
[self injectDataTaskDidBecomeDownloadTaskIntoDelegateClass:cls];
[self injectDownloadTaskDidWriteDataIntoDelegateClass:cls];
[self injectDownloadTaskDidFinishDownloadingIntoDelegateClass:cls];
}
這里基本對(duì)每一個(gè)代理函數(shù)都執(zhí)行了inject,實(shí)現(xiàn)思路基本一樣的,下面只調(diào)一個(gè)講:
inject方法實(shí)現(xiàn)
+ (void)injectWillSendRequestIntoDelegateClass:(Class)cls
{
SEL selector = @selector(connection:willSendRequest:redirectResponse:);
SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector];
Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
if (!protocol) {
protocol = @protocol(NSURLConnectionDelegate);
}
struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
typedef NSURLRequest *(^NSURLConnectionWillSendRequestBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response);
1.
NSURLConnectionWillSendRequestBlock undefinedBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
[[FLEXNetworkObserver sharedObserver] connection:connection willSendRequest:request redirectResponse:response delegate:slf];
return request;
};
2.
NSURLConnectionWillSendRequestBlock implementationBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
__block NSURLRequest *returnValue = nil;
[self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
undefinedBlock(slf, connection, request, response);
} originalImplementationBlock:^{
returnValue = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, connection, request, response);
}];
return returnValue;
};
[FLEXUtility replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
}
- 由于需要進(jìn)行網(wǎng)絡(luò)抓包,這意味著如果該類沒有實(shí)現(xiàn)對(duì)應(yīng)的代理方法名,也需要實(shí)現(xiàn)一個(gè),這就是
undefinedBlock
的作用,可以看出抓包的信息源自于這里。 -
implementationBlock
是新方法的實(shí)現(xiàn)block。 - 顧名思義,就是替換方法實(shí)現(xiàn),如果原本沒有這個(gè)方法名,就增加一個(gè)實(shí)現(xiàn)是undefinedBlock的方法
sniff那個(gè)函數(shù)的實(shí)現(xiàn)如下:
+ (void)sniffWithoutDuplicationForObject:(NSObject *)object selector:(SEL)selector sniffingBlock:(void (^)(void))sniffingBlock originalImplementationBlock:(void (^)(void))originalImplementationBlock
{
1.
if (!object) {
originalImplementationBlock();
return;
}
const void *key = selector;
2.
if (!objc_getAssociatedObject(object, key)) {
sniffingBlock();
}
objc_setAssociatedObject(object, key, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
originalImplementationBlock();
objc_setAssociatedObject(object, key, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- 檢查
object
是否存在,這里的object
指的是傳進(jìn)來的NSURLSession或者NSURLConnection,如果不存在,就不需要抓包,調(diào)用原函數(shù)即可 - 先調(diào)用
undefinedBlock
的函數(shù),再調(diào)用原來的實(shí)現(xiàn),這里增加了一個(gè)變量防止這個(gè)代理方法被嵌套調(diào)用多次(AFNetworking
和SDWebImage
的網(wǎng)絡(luò)實(shí)現(xiàn)都存在嵌套調(diào)用的情況)
replaceImplementationOfSelector
方法方法實(shí)現(xiàn)如下:
+ (void)replaceImplementationOfSelector:(SEL)selector withSelector:(SEL)swizzledSelector forClass:(Class)cls withMethodDescription:(struct objc_method_description)methodDescription implementationBlock:(id)implementationBlock undefinedBlock:(id)undefinedBlock
{
1.
if ([self instanceRespondsButDoesNotImplementSelector:selector class:cls]) {
return;
}
2.
IMP implementation = imp_implementationWithBlock((id)([cls instancesRespondToSelector:selector] ? implementationBlock : undefinedBlock));
3.
Method oldMethod = class_getInstanceMethod(cls, selector);
if (oldMethod) {
class_addMethod(cls, swizzledSelector, implementation, methodDescription.types);
Method newMethod = class_getInstanceMethod(cls, swizzledSelector);
method_exchangeImplementations(oldMethod, newMethod);
} else {
class_addMethod(cls, selector, implementation, methodDescription.types);
}
}
- 判斷該類是否只能響應(yīng)方法但并沒有實(shí)現(xiàn)方法,其實(shí)就是其父類實(shí)現(xiàn)了方法,這種場景就不進(jìn)行hook
- 如果這個(gè)方法已經(jīng)實(shí)現(xiàn),替換的block就是
implementationBlock
,否則就是undefinedBlock
- 執(zhí)行swizzle,這個(gè)swizzle跟原來的不太一樣,主要在于
swizzledSelector
并不是寫死在代碼里的方法,hook的時(shí)候需要添加上。此外,如果對(duì)象并不響應(yīng)這個(gè)方法,只需要添加一個(gè)原有的方法實(shí)現(xiàn)就行,不需要swizzle,此時(shí)調(diào)用的是undefinedBlock
,在里面并沒有調(diào)用swizzledSelector
。
對(duì)每個(gè)網(wǎng)絡(luò)請(qǐng)求的代理方法都這么做,就能手收集網(wǎng)絡(luò)請(qǐng)求的數(shù)據(jù)了,接下來就是將數(shù)據(jù)進(jìn)行記錄,并呈現(xiàn)在tableView上面。這里就不展開講了。