您好,登錄后才能下訂單哦!
AFNetworking是iOS界知名的網(wǎng)絡(luò)三方庫,現(xiàn)已完全取代了ASI。最新的AFNetworking3.0也早已從NSURLConnection切換到了NSURLSession,使用起來也更加方便。作為一名不斷探索的資深iOSer,還是要看看源碼提升下內(nèi)功。
首先看下AFNetworking的結(jié)構(gòu)及其繼承關(guān)系:
Class | SuperClass | Description |
---|---|---|
AFURLSessionManager |
NSObject |
①用于管理NSURLSession實例。②負(fù)責(zé)生成dataTask、uploadTask和downloadTask。 |
AFHTTPSessionManager |
AFURLSessionManager |
AFURLSessionManager的子類,封裝了網(wǎng)絡(luò)請求并提供了Convenience Methods發(fā)起HTTP請求。 |
AFHTTPRequestSerializer |
NSObject |
生成網(wǎng)絡(luò)請求所需的Request,包括對參數(shù)的處理。 |
AFHTTPResponseSerializer |
NSObject |
解析返回來的Response,并驗證合法性。 |
AFSecurityPolicy |
NSObject |
主要處理HTTPs通信。 |
AFURLSessionManagerTaskDelegate |
NSObject |
作為task的delegate,調(diào)用回調(diào)。 |
涉及的主要類都在上表中了,下面簡單說下其他的輔助類:
(1)_AFURLSessionTaskSwizzling
:這個類只做一件事:使用Method Swizzling更改NSURLSessionDataTask及其父類的resume
及suspend
實現(xiàn),在其調(diào)用時發(fā)送消息:AFNSURLSessionTaskDidResumeNotification
和AFNSURLSessionTaskDidSuspendNotification
即:
- (void)af_resume {
NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state");
NSURLSessionTaskState state = [self state];
[self af_resume];
if (state != NSURLSessionTaskStateRunning) {
[[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidResumeNotification object:self];
}
}
- (void)af_suspend {
NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state");
NSURLSessionTaskState state = [self state];
[self af_suspend];
if (state != NSURLSessionTaskStateSuspended) {
[[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidSuspendNotification object:self];
}
}
(2)AFJSONRequestSerializer
:是AFHTTPRequestSerializer
的子類,相比于AFHTTPRequestSerializer
,它增加了對parameters是否是合法JSON格式的校驗。在POST情況下,parameters會通過NSJSONSerialization轉(zhuǎn)化為NSData放到HTTPBody里。此外,header的Content-Type也會被設(shè)置為application/json
。
(3)AFQueryStringPair
:包含field
和value
屬性,用于表示參數(shù)(eg. name='layne'
),并且field和value要經(jīng)過“PercentEscaped”處理,處理函數(shù)如下:
NSString * AFPercentEscapedStringFromString(NSString *string) {
static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]];
// FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028
// return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
static NSUInteger const batchSize = 50;
NSUInteger index = 0;
NSMutableString *escaped = @"".mutableCopy;
while (index < string.length) {
NSUInteger length = MIN(string.length - index, batchSize);
NSRange range = NSMakeRange(index, length);
// To avoid breaking up character sequences such as emoji
range = [string rangeOfComposedCharacterSequencesForRange:range];
NSString *substring = [string substringWithRange:range];
NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
[escaped appendString:encoded];
index += range.length;
}
return escaped;
}
這里有兩點需要說明:
①對于字符截斷問題(eg.emoji),這里使用了:rangeOfComposedCharacterSequencesForRange:
,根據(jù)給定的range調(diào)整實際的range來防止字符截斷。
②這里設(shè)置了batchSize分塊進行escape。為啥要這么做?FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028
給出了具體解釋:
Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead.
簡單說就是,在8.1和8.2上超過100個中文字符會掛。
(4)AFStreamingMultipartFormData
用于multipart方式上傳的formData.
(5)AFHTTPBodyPart
(6)AFMultipartBodyStream
(7)AFJSONResponseSerializer
:AFHTTPResponseSerializer
的子類,解析JSON格式的response.
(8)AFXMLParserResponseSerializer
:AFHTTPResponseSerializer
的子類,解析(NSXMLParser
)XML格式的response.
(9)AFXMLDocumentResponseSerializer
:AFHTTPResponseSerializer
的子類,解析(NSXMLDocument
)XML格式的response.
(10)AFPropertyListResponseSerializer
:AFHTTPResponseSerializer
的子類,解析(NSXMLDocument
)PropertyList格式的response,
(11)AFImageResponseSerializer
:AFHTTPResponseSerializer
的子類,解析圖片response。
(12)AFCompoundResponseSerializer
:AFHTTPResponseSerializer
的子類,解析復(fù)合類型的response。
AFURLSessionManager
是管理網(wǎng)絡(luò)請求的主類,它的結(jié)構(gòu)如下:
管理著
一個session
(NSURLSession實例),用于發(fā)起網(wǎng)絡(luò)請求。
一個operationQueue
,用于執(zhí)行代理回調(diào)。
一個responseSerializer
(實現(xiàn)了AFURLResponseSerialization
),用于response解析。
一個securityPolicy
(AFSecurityPolicy
實例),用于HTTPs配置。
一個reachabilityManager
(AFNetworkReachabilityManager
實例),用于網(wǎng)絡(luò)連通性監(jiān)聽。
通過重寫tasks
、dataTasks
、uploadTasks
和downloadTasks
屬性的getter方法,使用getTasksWithCompletionHandler:
獲取session
管理的tasks。
提供多種生成task的函數(shù)。如:
-dataTaskWithRequest:completionHandler:
-dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
-uploadTaskWithRequest:fromFile:progress:completionHandler:
-uploadTaskWithRequest:fromData:progress:completionHandler:
-uploadTaskWithStreamedRequest:progress:completionHandler:
-downloadTaskWithRequest:progress:destination:completionHandler:
-downloadTaskWithResumeData:progress:destination:completionHandler:
監(jiān)控上傳/下載進度。
-uploadProgressForTask:
-downloadProgressForTask:
定義回調(diào)block屬性,每個block對應(yīng)NSURLSession相關(guān)的delegate方法。
@property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid;
@property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge;
@property (readwrite, nonatomic, copy) AFURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession AF_API_UNAVAILABLE(macos);
@property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection;
@property (readwrite, nonatomic, copy) AFURLSessionTaskDidReceiveAuthenticationChallengeBlock taskDidReceiveAuthenticationChallenge;
@property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream;
@property (readwrite, nonatomic, copy) AFURLSessionTaskDidSendBodyDataBlock taskDidSendBodyData;
@property (readwrite, nonatomic, copy) AFURLSessionTaskDidCompleteBlock taskDidComplete;
#if AF_CAN_INCLUDE_SESSION_TASK_METRICS
@property (readwrite, nonatomic, copy) AFURLSessionTaskDidFinishCollectingMetricsBlock taskDidFinishCollectingMetrics;
#endif
@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveResponseBlock dataTaskDidReceiveResponse;
@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidBecomeDownloadTaskBlock dataTaskDidBecomeDownloadTask;
@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveDataBlock dataTaskDidReceiveData;
@property (readwrite, nonatomic, copy) AFURLSessionDataTaskWillCacheResponseBlock dataTaskWillCacheResponse;
@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading;
@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidWriteDataBlock downloadTaskDidWriteData;
@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidResumeBlock downloadTaskDidResume;
聲明了常量。
//通知
AFNetworkingTaskDidResumeNotification
AFNetworkingTaskDidCompleteNotification
AFNetworkingTaskDidSuspendNotification
AFURLSessionDidInvalidateNotification
AFURLSessionDownloadTaskDidFailToMoveFileNotification
//通知AFNetworkingTaskDidCompleteNotification中userInfo的key
AFNetworkingTaskDidCompleteResponseDataKey
AFNetworkingTaskDidCompleteSerializedResponseKey
AFNetworkingTaskDidCompleteResponseSerializerKey
AFNetworkingTaskDidCompleteAssetPathKey
AFNetworkingTaskDidCompleteErrorKey
在生成task時為每個task生成對應(yīng)的delegate(AFURLSessionManagerTaskDelegate
實例),并使用{<taskID:delegate>}的形式保存在可變字典mutableTaskDelegatesKeyedByTaskIdentifier
中。
作為NSURLSession的delegate,實現(xiàn)的delegate方法有:
/* ----------NSURLSessionDelegate---------- */
//執(zhí)行sessionDidBecomeInvalid block并發(fā)通知
- (void)URLSession:didBecomeInvalidWithError:
//生成disposition(NSURLSessionAuthChallengeDisposition實例),并調(diào)用completionHandler
- (void)URLSession:didReceiveChallenge:completionHandler:
//執(zhí)行didFinishEventsForBackgroundURLSession block
- (void)URLSessionDidFinishEventsForBackgroundURLSession:
/* ----------NSURLSessionTaskDelegate---------- */
//執(zhí)行taskWillPerformHTTPRedirectionBlock生成新的request,并調(diào)用completionHandler
- (void)URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:
//生成disposition(NSURLSessionAuthChallengeDisposition實例),并調(diào)用completionHandler
- (void)URLSession:task:didReceiveChallenge:completionHandler:
//生成inputStream(NSInputStream實例),并調(diào)用completionHandler
- (void)URLSession:task:needNewBodyStream:
//轉(zhuǎn)到task delegate中執(zhí)行,并執(zhí)行taskDidSendBodyData block
- (void)URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:
//轉(zhuǎn)到task delegate中執(zhí)行,并執(zhí)行taskDidComplete block
- (void)URLSession:task:didCompleteWithError:
/* ----------NSURLSessionDataDelegate---------- */
//執(zhí)行dataTaskDidReceiveResponse block生成disposition,并調(diào)用completionHandler
- (void)URLSession:dataTask:didReceiveResponse:completionHandler:
//重新設(shè)置task delegate,并調(diào)用dataTaskDidBecomeDownloadTask block
- (void)URLSession:dataTask:didBecomeDownloadTask:
//轉(zhuǎn)到task delegate中執(zhí)行,并調(diào)用dataTaskDidReceiveData block
- (void)URLSession:dataTask:didReceiveData:
//執(zhí)行dataTaskWillCacheResponse block生成cacheResponse,并調(diào)用completionHandler
- (void)URLSession:dataTask:willCacheResponse:completionHandler:
/* ----------NSURLSessionDownloadDelegate---------- */
//轉(zhuǎn)到task delegate中執(zhí)行,并移動文件
- (void)URLSession:downloadTask:didFinishDownloadingToURL:
//轉(zhuǎn)到task delegate中執(zhí)行,并執(zhí)行downloadTaskDidWriteData block
- (void)URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:
//轉(zhuǎn)到task delegate中執(zhí)行,并執(zhí)行downloadTaskDidResume block
- (void)URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:
AFURLSessionManagerTaskDelegate
這個類雖然后綴是·-Delegate
,但它并不是一個協(xié)議,而是一個繼承自NSObject
的類。它和AFURLSessionManager
都定義在文件AFURLSessionManager.m
中。它的實例作為task的代理使用。
包含一個manager
屬性,使用weak
回指使用它的AFURLSessionManager
實例。
包含控制上傳和下載進度的屬性uploadProgress
和downloadProgress
(均為NSProgress
實例),通過KVO監(jiān)測各自的fractionCompleted
,從而在結(jié)束時調(diào)用downloadProgressBlock
和uploadProgressBlock
。
實現(xiàn)的delegate包括:
/* ----------NSURLSessionTaskDelegate---------- */
//構(gòu)造userInfo,并使用manager的responseSerializer解析response,最后調(diào)用self.completionHandler.
- (void)URLSession:task:didCompleteWithError:
//更新uploadProgress屬性
- (void)URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:
/* ----------NSURLSessionDataTask---------- */
//更新downloadProgress屬性,并用mutableData保存接收到的數(shù)據(jù)
- (void)URLSession:dataTask:didReceiveData:
/* ----------NSURLSessionDownloadTask-------- */
//更新downloadProgress屬性
- (void)URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:
//更新downloadProgress屬性
- (void)URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:
//清空downloadFileURL(nil),并移動文件
- (void)URLSession:downloadTask:didFinishDownloadingToURL:
注:AFURLSessionManagerTaskDelegate實例本身不持有task,它們之間的代理關(guān)系是以{<taskID:delegate>}的形式保存在可變字典mutableTaskDelegatesKeyedByTaskIdentifier
中的。
AFHTTPSessionManager
是AFURLSessionManager
的子類,它針對HTTP請求封裝了更為便利的方法。它的結(jié)構(gòu)如下:
主要包含requestSerializer
(AFHTTPRequestSerializer
實例)和responseSerializer
(AFHTTPResponseSerializer
實例),分別用于request的封裝及response的解析。
提供三個實例初始化方法:
+ (instancetype)manager;
- (instancetype)initWithBaseURL:(nullable NSURL *)url;
- (instancetype)initWithBaseURL:(nullable NSURL *)url sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration;
最終調(diào)用的都是第三個函數(shù)。
封裝的Convenience Method如下:
- GET:parameters:headers:progress:success:failure:
- POST:parameters:headers:progress:success:failure:
- POST:paramters:headers:constructingBodyWithBlock:progress:success:failure:
- HEAD:parameters:headers:success:failure:
- PUT:parameters:headers:success:failure:
- PATCH:parameters:headers:success:failure:
- DELETE:paramaters:headers:success:failure:
注:上面只列出了有效的方法,其他的都已經(jīng)被標(biāo)記為DEPRECATED_ATTRIBUTE
了。
除了包含...constructingBodyWithBlock…
的POST函數(shù)外,其余的convenience methods都是通過以下函數(shù)生成對應(yīng)的dataTask:
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:
URLString:
parameters:
uploadProgress:
downloadProgress:
success:
failure:
在上述函數(shù)中,requestSerializer
會通過HTTPMethod、URLString和parameters生成request
,然后會調(diào)用父類的:dataTaskWithRequest:uploadProgress:downloadProgress: completionHandler:
生成dataTask并返回。返回的dataTask會被resume啟動。
AFHTTPRequestSerializer
繼承自NSObject
,用于封裝request。
實現(xiàn)了協(xié)議AFURLRequestSerialization
。這個協(xié)議只有一個函數(shù):
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error;
用于將參數(shù)包含到原始request中形成新的request。
使用數(shù)組mutableHTTPRequestHeaders
保存要包含在request header中的數(shù)據(jù)。默認(rèn)包含Accept-Language
和User-Agent
。其中,在設(shè)置User-Agent
時,為了保證ASCII編碼規(guī)則,作者使用了ICU文本變換。
CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)
ICU 庫提供了一整套強大的文本變換功能,可以實現(xiàn)不用語系之間的字符轉(zhuǎn)換,如漢字轉(zhuǎn)拼音。在上面的例子中,User-Agent
字段會先被轉(zhuǎn)換為Latin,接著變換為Latin-ASCII,最后清除所有不是ASCII的字符。 其他的變換可參考 ICU 用戶手冊。
采用KVO機制監(jiān)測相關(guān)屬性,若用戶設(shè)置了對應(yīng)屬性,該屬性會被記錄下來,在生成request時加入。
allowsCellularAccess
cachePolicy
HTTPShouldHandleCookies
HTTPShouldUsePipelining
networkServiceType
timeoutInterval
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key
,禁止以上6個字段的KVO自動觸發(fā)。willChangeValueForKey
和didChangeValueForKey
手動觸發(fā)KVO。生成request使用以下函數(shù):
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
error:(NSError *__autoreleasing *)error
執(zhí)行的操作包括:
① 根據(jù)URLString和method創(chuàng)建mutableRequest
NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
mutableRequest.HTTPMethod = method;
② 使用KVC將KVO監(jiān)測的6個字段(用戶設(shè)置過的)包含進mutableRequest中。
for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) {
[mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath];
}
}
③ 調(diào)用AFURLRequestSerialization
協(xié)議方法- requestBySerializingRequest: withParameters: error:
。在這個協(xié)議方法內(nèi)部執(zhí)行:
name=layne$age=30&job=engineer
。AFJSONRequestSerializer
是AFHTTPRequestSerializer
的子類,使用NSJSONSerialization
將參數(shù)編碼成JSON格式,并設(shè)置Content-Type
為application/json
。它重寫了AFURLRequestSerialization
協(xié)議方法:
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(request);
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
return [super requestBySerializingRequest:request withParameters:parameters error:error];
}//若為GET/HEAD/DELETE方法,由于參數(shù)都拼接在URL中,因此無所謂json不json,直接調(diào)用父類的方法即可。
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
if (![request valueForHTTPHeaderField:field]) {
[mutableRequest setValue:value forHTTPHeaderField:field];
}
}];//更新header數(shù)據(jù)
if (parameters) {
if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
[mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
}//設(shè)置Content-Type字段為“application/json”
if (![NSJSONSerialization isValidJSONObject:parameters]) {
if (error) {
NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"The `parameters` argument is not valid JSON.", @"AFNetworking", nil)};
*error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
}
return nil;
}//非法的json格式(NSDictionary)數(shù)據(jù)
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error];//json序列化
if (!jsonData) {
return nil;
}
[mutableRequest setHTTPBody:jsonData];
}
return mutableRequest;
}
AFHTTPResonseSerializer
繼承自NSObject
,實現(xiàn)了AFURLResponseSerialization
協(xié)議:
- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response
data:(nullable NSData *)data
error:(NSError * _Nullable __autoreleasing *)error;
在協(xié)議方法中根據(jù)acceptableStatusCodes
和acceptableContentTypes
判斷response合法性。
AFJSONResponseSerializer
是AFHTTPResponseSerializer
的子類。
設(shè)置acceptableContentTypes
指定合法的content-type:
application/json
text/json
text/javascript
重寫AFURLResponseSerialization
協(xié)議方法:
- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response
data:(nullable NSData *)data
error:(NSError * _Nullable __autoreleasing *)error;
在內(nèi)部:
(1)根據(jù)acceptableStatusCodes
和acceptableContentTypes
判斷response合法性;
(2)使用NSJSONSerialization
將data轉(zhuǎn)換為NSDictionary
(3)根據(jù)removesKeysWithNullValues
的值決定是否將NSDictionary中NSNull的數(shù)據(jù)清除。
以上就是AFNetworking主要的類結(jié)構(gòu)及其功能。下一篇博客我們會以一個簡單的POST請求來走一遍邏輯,看看AFN到底是如何工作的。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。