AFNetworking2.0源码解析<二> -- 构建普通请求: 格式化请求参数,生成HTTP Header + 构建multipart请求
How to implement a CoreFoundation toll-free bridged NSInputStream subclass
AFNetworking2.0源码解析<三> -- HTTPS建立过程+CA防止中间人+SSL Pinning
关于数字证书:浅析数字证书
AFNetworking源码解析<四> -- AFURLResponseSerialization(2Method+JSON解析+图片解压)
AFNetworking 2.0 Migration Guide
AFNetworking 3.0 Migration Guide
AFURLSessionManager
.h -- NSURLSession + NSOperationQueue,AFURLResponseSerialization + AFSecurityPolicy + AFNetworkReachabilityManager
data/upload/download/Tasks
~~~
.m --
队列2 + 常量 + block
AFURLSessionManagerTaskDelegate
init:(upload/downloadProgress)
setupProgressForTask: -- 用upload和download的NSProgress = NSURLSessionTask的属性 + 上传下载KVO
cleanUpProgressForTask: -- remove KVO
observeValueForKeyPath:ofObject:change:context: -- 触发
URLSession:task:didCompleteWithError: - userInfoDict[ResponseSerializer][AssetPath][ResponseData],(error -- [Error] + 异步主队列completionHandler + CompleteNotification(userInfoDict) ) +
responseSerializer(默认JSON解析) + [SerializedResponse][Error] + completionHandler + CompleteNotification(userInfoDict)
URLSession:dataTask:didReceiveData: - appendData
URLSession:downloadTask:didFinishDownloadingToURL: - (FinishDownloadingBlock() -> downloadFileURL) + moveItemAtURL:toURL: + error->FailMoveNotification
static inline void af_swizzleSelector & BOOL af_addMethod -- methodSwizzling
_AFURLSessionTaskSwizzling
+load - 当前类和父类的resume比较+和原始AFResume比较,↓↓↓
+swizzleResumeAndSuspendMethodForClass: -- MS - af_resume <=> resume & af_suspend <=> suspend
state - StateCanceling
af_resume - [self state] + resume + DidResume通知
af_suspend - [self state] + suspend + DidSuspend通知
AFURLSessionManager
initWithSessionConfiguration: -- 初始化(session+responseSerializer+securityPolicy+reachabilityManager)
taskDidResume && taskDidSuspend: -- 通知方法,同一对象发送的通知->异步主队列DidSuspend/Resume通知
AFURLSessionManagerTaskDelegate - getter - [task.taskIdentifier]=delegate
setter -- setupProgressForTask(delegate初始化) + addNotificationObserverForTask
addDelegateForData/Upload/DownloadTask:upload/downloadProgress:/destination:completionHandler:
- delegate(各种block/FinishDownloadingBlock) -> setForData/Upload/DownloadTask
removeDelegateForTask: - (delegate cleanUp) + remove通知
(tasks + dataTasks + uploadTasks + downloadTasks) - getter -> tasksForKeyPath([self.session getTasksWithCompletionHandler~~])
invalidateSessionCancelingTasks: -- session2M
dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: - 安全创建dataTask -> addDelegateForDataTask
uploadTaskWith/StreamedRequest:fromFile/Data:progress:completionHandler: - 安全创建uploadTask (重新创建) -> appDelegateForUploadTask
downloadTaskWithRequest/ResumeData:progress:destination:completionHandler: - 同
各种setBlock(15)
NSURLSessionDelegate
-URLSession:didBecomeInvalidWithError: - BecomeInvalidBlock + notification
-URLSession:didReceiveChallenge:completionHandler: - i. if --验证挑战Block ->返回disposition else --服务器信任方法-> (securityPolicy)安全评估->证书验证
ii. completionBlock(disposition, credential)
NSURLSessionTaskDelegate
-URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler: - HTTP重定向Block + completionBlock
-URLSession:task:didReceiveChallenge:completionHandler: - i. if --验证挑战block ->返回disposition else --服务器信任方法->安全评估->证书验证
ii. completionBlock(disposition, credential)
-URLSession:task:needNewBodyStream: - if -- streamBlock -> 返回inputStream else -- HTTPBodyStream存在&&实现协议-> copy + completionBlock()
-URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend: - 原始请求头"Content-Length" -> totalUnitCount + DidSendBodyDataBlock()
-URLSession:task:didCompleteWithError: - [delegate URLSession:task:didCompleteWithError:](拼接各种userInfo,通知发送) + removeDelegate + taskDidCompleteBlock
NSURLSessionDataDelegate
-URLSession:dataTask:didReceiveResponse:completionHandler: - DidReceiveResponseBlock + completionBlock
-URLSession:dataTask:didBecomeDownloadTask: - remove-dataTask + set-downloadTask + becomeDownloadTaskBlock()
-URLSession:dataTask:didReceiveData: - delegate的didReceiveData(appendData) + receiveDataBlock()
-URLSession:dataTask:willCacheResponse:completionHandler: - cacheResponseBlock() + completionBlock
-URLSessionDidFinishEventsForBackgroundURLSession: - 异步主队列(后台session完成事件block)
NSURLSessionDownloadDelegate
-URLSession:downloadTask:didFinishDownloadingToURL: - (DidFinishDownloadingBlock -> fileURL) + moveItemAtURL:toURL: + FailMoveNotification + delegate类似方法(downloadFileURL + FailMoveNotification)
-URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite: - DidWriteDataBlock
-URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes: - DidResumeBlock
NSSecureCoding -- sessionConfig的编解码
NSCopying
AFHTTPSessionManager
.h --
.m --
initWithBaseURL:sessionConfiguration: -- url + 请求响应Serializer
Request & ResponseSerializer - setter
GET:parameters:/progress:success:failure: **
HEAD:parameters:success:failure: **
POST:parameters:/progress:success:failure: **
❤❤❤ POST:parameters:constructingBodyWithBlock:/progress:success:failure: - i. requestSerializer(组装AFHTTPBodyPart + HTTPBodyStream + HeaderField) + (nil OR failureBlock)
ii. 父类StreamedRequest:(安全创建uploadTask -> addDelegateForUploadTask)
PUT:parameters:success:failure: **
PATCH:parameters:success:failure: **
DELETE:parameters:success:failure: **
❤❤❤ dataTaskWithHTTPMethod:URLString:parameters:uploadProgress:
downloadProgress:success:failure: - i. requestSerializer(请求前的配置- (url + HTTPMethod) + (现有ObservedKeyPaths -> [request setValue: forKey:]) + HTTPHeaderField +通过parameters转换为queryString + HTTPMethod做不同设置 ) + (nil OR failureBlock)
ii. ->父类dataTaskWithRequest:(安全创建uploadTask -> addDelegateForUploadTask)
NSSecureCoding -- 编解码5
NSCopying
iOS. PercentEscape是错用的URLEncode,看看AFN和Facebook吧
苹果的编码 != URLEncode
(1)当遇到发送网络请求的参数中有汉字的情况,使用stringByAddingPercentEscapesUsingEncoding:进行转义,这样带有汉字的urlString就会将每个汉字转成相应的unicode编码对应的3个%形式,这叫urlEncode(每个能写后端的语言都有的方法),但是苹果的stringByAddingPercentEscapesUsingEncoding:却不是urlEncode。
&不会转码 - 产生这种情况的原因是:百分号转义不等于URLEncode,该编码不同于URL编码,由于不会对&字符编码,因此不会改变URL参数的分隔。URL编码会编码&、?与其他标点符号。
(2)iOS 7.0 - stringByAddingPercentEncodingWithAllowedCharacters: 需要传递一个参数:这个参数是一个字符集,表示:在进行转义过程中,不会对这个字符集中包含的字符进行转义,而保持原样保留下来。
[NSCharacterSet letterCharacterSet] 来保证字母不被转义
MORE:遇到queryString中的表单域也需要转义的情况 - person[contact] = 13801001234
[mutableCharSet addCharactersInString:@"[]"];
(3)AFN
GET:@"https://www.baidu.com/s"
parameters:@{@"ie":@"UTF-8",@"wd":@"汉字&ss"};
success:nil failure:nil
AFN对queryString的组装是这样进行的:
AFN会将parameters传递的字典通过将每个表单元素的 field 和 value 进行 urlcode 之后拼接,然后再直接附加在传递的URLString后面(当然,如果是POST方式就不是附加了,而是将拼好的串放到HTTP body中)。
(4) AFN URLEncode - 将字典转为queryString的模块
- 请求前:构建request的header和queryString、uploadContent和配置(如超时等),这部分的功能在AFURLRequestSerialization中
- 请求中:分别有基于NSURLConnection的访问(3.0移除)和基于NSURLSession的访问模块
- 请求后:错误处理 OR 成功处理:数据格式转换和解析,主要在AFURLResponseSerialization中
NSArray* AFQueryStringPairsFromKeyAndValue(NSString*key, id value);
<1> 利用AFQueryStringPairsFromKeyAndValue函数将parameters字典中的每个key-value对取出,将每个key-value对构建为AFQueryStringPair对象,放到一个数组中。
<2> 在AFQueryStringFromParameters方法内部遍历这个数组(每个元素为AFQueryStringPair对象),使用AFQueryStringPair类的转义方法 URLEncodedStringValue 将 AFQueryStringPair 转为字符串,将这些字符串存入新的数组中。这样新数组中的每个元素就是转义之后的field=value字符串,最后用&将数组元素连接即可。
NSString* AFPercentEscapedStringFromString(NSString*string)
(5)queryString转为字典的需求
Facebook的facebook-ios-sdk
+ (NSDictionary*)dictionaryWithQueryString:(NSString*)queryString;
+ (NSString*)URLDecode:(NSString*)value;
AFURLRequestSerialization
.h --
AFPercentEscapedStringFromString() + AFQueryStringFromParameters()
@protocol - requestBySerializingRequest:withParameters:error:
AFHTTPRequestSerializer
+serializer
- HTTPHeaderField setter & getter
- AuthorizationHeaderField
- requestWithMethod:URLString:parameters:error:
multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:
- requestWithMultipartFormRequest:writingStreamContentsToFile:completionHandler:
@protocol AFMultipartFormData - 7
AFJSONRequestSerializer
AFPropertyListRequestSerializer
.m --
AFPercentEscapedStringFromString - allowCharacterSet中移除编码字符+ stringByAddingPercentEncodingWithAllowedCharacters
AFQueryStringPair
- initWithField:value:
- URLEncodedStringValue -> AFPercentEscapedStringFromString(NSString *string) = habit%5B%5D=%E6%B8%B8%E6%B3%B3
通过parameters转换为queryString AFQueryStringFromParameters(URLEncodedStringValue) -> AFQueryStringPairsFromDictionary -> AFQueryStringPairsFromKeyAndValue(组装NSArray,内部是AFQueryStringPair对象)
AFHTTPRequestSerializerObservedKeyPaths - 单例ObservedKeyPaths = @[allowsCellularAccess, cachePolicy, HTTPShouldHandleCookies/UsePipelining, networkServiceType, timeoutInterval]
AFHTTPRequestSerializer
-init - "Accept-Language"/User-Agent HeaderField + HTTP Method + 观察ObservedKeyPaths中属性
allowsCellularAccess/cachePolicy/HTTPShouldHandleCookies/UsePipelining/networkServiceType/timeoutInterval 手动触发KVO
HTTPRequestHeaders setter & getter
-setAuthorizationHeaderFieldWithUsername:password: - NSData(NSString) -> NSString(NSData base64) -> setHTTPRequestHeaders
- requestWithMethod:URLString:parameters:error: - (url + HTTPMethod) + 现有ObservedKeyPaths -> [request setValue: forKey:] + (HTTPHeaderField +通过parameters转换为queryString + HTTPMethod做不同设置)
-multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:
AFStreamingMultipartFormData + (pair.value -> data +组装AFHTTPBodyPart) + block,first&last设置YES + HTTPBodyStream + Content-Type/-Length HeaderField
-requestWithMultipartFormRequest:writingStreamContentsToFile:completionHandler: - ioStream - (read:maxLength: & write:maxLength:)
-requestBySerializingRequest:withParameters:error: - HTTPHeaderField +通过parameters转换为queryString + HTTPMethod做不同设置
NSKeyValueObserving - 在ObservedKeyPaths中手动调用 + 收到KVO,非NSNull->add
NSSecureCoding - mutableHTTPRequestHeaders & queryStringSerializationStyle的编解码
NSCopying
AFCreateMultipartFormBoundary - @"Boundary+%08X%08X"
AFMultipartFormInitial/Encapsulation/FinalBoundary - ~~
AFContentTypeForPathExtension - 通过pathExtension返回contentType
AFHTTPBodyPart
-init -> transitionToNextPhase - - (runloop&open + close)
-inputStream - 根据body类型设置_inputStream(set是.body=~, get是.inputStream)
-stringForHeaders - headers的(key: value/r/n ~~~)组成的string
-contentLength - AFHTTPBodyPart的contentLength = (2BoundaryData+headersData+_bodyContentLength)
-hasBytesAvailable - 根据streamStatus返回是否可用
-read:maxLength: - _phase->(2BoundaryData+HeaderData) -> ↓↓↓
-readData:intoBuffer:maxLength: - [data getBytes:buffer range:range] + _phaseReadOffset + NextPhaseIfNeed
NSCopying
AFMultipartBodyStream
-initWithStringEncoding:
-setInitialAndFinalBoundaries - first&last设置YES
-read:maxLength: - [HTTPBodyPart read:maxLength:]
-open - (statusOpen + boundaryYES + Enumerator)
NSCopying - 内部AFHTTPBodyPart copy + BoundaryYES
AFStreamingMultipartFormData
-initWithURLRequest:stringEncoding:
-appendPartWithFileURL:name:error: - fileName+mimeType -> ↓↓↓
-appendPartWithFileURL:name:fileName:mimeType:error: - (不是fileURL ||返回是否URL's资源存在且可达) -> error(userInfo) + 拼接AFHTTPBodyPart(Headers=(key:Content-Disposition/-Type value:~)+length=fileAttributes[NSFileSize])
-appendPartWithInputStream:name:fileName:length:mimeType: - 拼接AFHTTPBodyPart(Headers=(key:Content-Disposition/-Type value:~)
-appendPartWithFileData:name:fileName:mimeType:(2Headers+data) -> **
-appendPartWithFormData:name:(Headers+data) -> appendPartWithHeaders:body:(组装AFHTTPBodyPart) - **
-requestByFinalizingMultipartFormData - first&last设置YES + HTTPBodyStream + Content-Type/-Length HeaderField
AFJSONRequestSerializer
-requestBySerializingRequest:withParameters:error: - @"GET", @"HEAD", @"DELETE"其中之一-> [super ~~] OR (HTTPRequestHeaders -> mutableRequestHeaders) + (hasParameters -> JSON头+HTTPBody:JSON数据)
NSSecureCoding - writingOptions的编解码
NSCopying
AFPropertyListRequestSerializer
-requestBySerializingRequest:withParameters:error: - @"GET", @"HEAD", @"DELETE"其中之一-> [super ~~] OR (HTTPRequestHeaders -> mutableRequestHeaders) + (hasParameters -> x-plist头+HTTPBody:PList数据)
NSSecureCoding - format&writeOptions的编解码
NSCopying
AFURLResponseSerialization
.h --
@protocol - responseObjectForResponse:data:error:
AFHTTPResponseSerializer
+serializer
-validateResponse:data:error: -- 验证响应是否有效
AFJSONResponseSerializer
+serializerWithReadingOptions:
AFXMLParserResponseSerializer
AFPropertyListResponseSerializer
+serializerWithFormat:readOptions:
AFImageResponseSerializer
AFCompoundResponseSerializer
+compoundSerializerWithResponseSerializers:
.m --
AFErrorWithUnderlyingError
AFErrorOrUnderlyingErrorHasCodeInDomain
AFJSONObjectByRemovingKeysWithNullValues - 递归
AFHTTPResponseSerializer
NSSecureCoding - acceptableStatusCodes & acceptableContentTypes的编解码
NSCopying
AFJSONResponseSerializer
-init - @"application/json",@"text/json",@"text/javascript"
-responseObjectForResponse:data:error: - 响应有效性 + (length > 0 && 非空格=>解析) + 去(key - value:(nil OR NSNull)) + 返回
NSSecureCoding - readingOptions & removesKeysWithNullValues的编解码
NSCopying
AFXMLParserResponseSerializer
-init - @"application/xml",@"text/xml"
-responseObjectForResponse:data:error: - 响应有效性 + NSXMLParserWithData
AFPropertyListResponseSerializer
-init - @"application/x-plist"
-responseObjectForResponse:data:error: - 响应有效性 + data ->解析 + 返回
NSSecureCoding - format & readOptions的编解码
NSCopying
UIImage (AFNetworkingSafeImageLoading)
+af_safeImageWithData - 单例锁+锁imageWithData
AFImageWithDataAtScale - 安全初始化 + 动图返回 + 初始化withScale
AFInflatedImageFromResponseWithDataAtScale - 解码图片
AFImageResponseSerializer
-init - @"image/tiff ~~~"
-responseObjectForResponse:data:error: - 响应有效性 + AFInflatedImageFromResponseWithDataAtScale解码图片 OR AFImageWithDataAtScale创建
NSSecureCoding - imageScale & automaticallyInflatesResponseImage的编解码
NSCopying
AFCompoundResponseSerializer
-responseObjectForResponse:data:error: - 遍历验证响应 OR 返回super
NSSecureCoding - responseSerializers的编解码
NSCopying
AFSecurityPolicy - 封装了证书验证的过程
.h -- 系统信任CA机构列表验证 + SSL Pinning
+certificatesInBundle:
+defaultPolicy
+policyWithPinningMode:withPinnedCertificates:
-evaluateServerTrust:forDomain:
.m --
AFSecKeyIsEqualToKey - isEqual:
AFPublicKeyForCertificate - certificateData->PublicKey
AFServerTrustIsValid - SecTrustEvaluate -> Unspecified && Proceed
AFCertificateTrustChainForServerTrust - 遍历serverTrust的SecCertificateRef —>拿Data - [trustChain add:certificateData]
AFPublicKeyTrustChainForServerTrust - 遍历serverTrust的(SecCertificateRef+policy+SecTrustRef) -> (trust+&result) -> [trustChain add:copy(publicKey)]
AFSecurityPolicy
+certificatesInBundle: - (本地.cer - [certificatesSet add:certificateData])
+defaultPinnedCertificates - 单例 + ↑↑↑
+defaultPolicy - 验证域名+ None
+policyWithPinningMode:withPinnedCertificates: - SSLPinningMode + ↓↓↓
+setPinnedCertificates: - 由本地的pinnedCertificates(cerNSData) -> AFPublicKeyForCertificate() = pinnedPublicKeys
-evaluateServerTrust:forDomain: - if + (验证域名=SSL->SecTrustSetPolicies) + ~ + Certificate -> (本地或外设pinnedCertificates(cerData)->SecCertificateCreateWithData()->MArray=AnchorCers AND AFServerTrustIsValid()->= serverTrust(CertificateData))
PublicKey -> serverTrust的cer对应的publicKeys AND 本地pinnedPublicKey =有一个相等
NSSecureCoding - SSLPinningMode&allowInvalidCertificates&validatesDomainName&pinnedCertificates的编解码
copyWithZone
AFNetworkReachabilityManager
.h --
+manager
+managerForDomain/Address:
-initWithReachability:
-startMonitoring / stopMonitoring
.m --
AFStringFromNetworkReachabilityStatus - 网络status返回description
AFNetworkReachabilityStatusForFlags - SCNetworkFlags各种& -> AFNetworkStatus
AFPostReachabilityStatusChange - flags->status +异步主队列(block +通知(userInfo:status))
AFNetworkReachabilityManager
+sharedManager: - +manager(address)->managerForAddress:
+managerForDomain: - domain->reachability->manager
+managerForAddress: - address->reachability->manager
+manager: - address -> ↑↑↑
-initWithReachability: - 网络可达&状态
-startMonitoring: - callback(设置status +回调StatusBlock(status)) -> (context -> setCallback(Callback) -> runloop)
异步后台SCNetworkGetFlags->AFPostStatusChange(status->post通知)
-stopMonitoring: - SCNetworkReachabilityUnscheduleFromRunLoop()
-keyPathsForValuesAffectingValueForKey: - 当reachable+reachableViaWWAN+reachableViaWiFi发生变化,被认为networkReachabilityStatus发生变化,发出通知
AFAutoPurgingImageCache
.h --
@protocol - AFImageCache
-addImage:withIdentifier:
removeImageWithIdentifier:
removeAllImages:
imageWithIdentifier:
@protocol - AFImageRequestCache
addImage:forRequest:withAdditionalIdentifier:
removeImageforRequest:withAdditionalIdentifier:
imageforRequest:withAdditionalIdentifier:
AFAutoPurgingImageCache
initWithMemoryCapacity:preferredMemoryCapacity:
.m --
AFCachedImage = Model
initWithImage:identifier:
AFAutoPurgingImageCache - cachedImagesDict
initWithMemoryCapacity:preferredMemoryCapacity: - 初始化+并发队列+内存警告removeAll通知
addImage:withIdentifier: - i. 阻塞异步i.并发队列-判断previous+(cachedImages+currentMemoryUsage)Add ii. 自动清除最早时间图片-拿cachedImagesDict的所有values(images)按lastAccessDate排序-> remove +减少currentMemoryUsage
removeImageWithIdentifier/AllImages: - 阻塞同步并发队列- removeObjectForKey/AllObjects
imageCacheKeyFromURLRequest:withAdditionalIdentifier: - request.URL.absoluteString
AFImageDownloader
-- NSURLCache + AFAutoPurgingImageCache
.h --
AFImageDownloadReceipt
AFImageDownloader
initWithSessionManager:downloadPrioritization:maximumActiveDownloads:imageCache:
-downloadImageForURLRequest:/withReceiptID:success:failure:
-cancelTaskForImageDownloadReceipt:
.m --
AFImageDownloaderResponseHandler - uuid + successBlock + failureBlock
-initWithUUID:success:failure:
AFImageDownloaderMergedTask - URLIdentifier + identifier + task +responseHandlersArray
-initWithURLIdentifier:identifier:task:
AFImageDownloadReceipt - task + receiptID
-initWithReceiptID:task:
AFImageDownloader
+defaultURLCache(内存缓存20M + 磁盘缓存150M)
+defaultURLSessionConfiguration(各种配置+defaultURLCache)
-init(defaultConfiguration + AFImageResponseSerializer ->> sessionManager + AFAutoPurgingImageCache) ---------> initWithSessionManager:downloadPrioritization:maximumActiveDownloads:imageCache - 各种+串行&并发队列
+defaultInstance - init
↑↑↑URLCache -> SessionConfig -> SessionManager -> AFImageDownloader
-downloadImageForURLRequest:withReceiptID:success:failure: - 同步串行( 1.取现存的mergedTask,拼接responseHandler -> add,return task
2. 如果缓存策略允许,尝试从图片缓存加载图片,!=nil & success ->异步主队列回调
3. 通过AFHTTPSessionManager创建dataTask) --> 异步并发队列(成功 -> 同步串行removeMergedTask,error - 遍历mergedTask.responseHandlersArray(异步主队列回调所有handler.failureBlock),noError -缓存图片 + 遍历(异步主队列回调所有hander.successBlock)
同步串行ActiveTaskCount-- + 同步串行-出队列==suspend -> resume)
4. 获得createdTask,拼接handler->拼接mergedTask(add拼接handler) -> mergedTasks[key:URLIdentifier value:mergedTask]
5. 开始mergedTask OR入队mergedTask --- return task
6. return拼接receipt
-cancelTaskForImageDownloadReceipt
同步串行(1. 拿mergedTask.responseHandlers中是否有uudi==imageDownloadReceipt.receiptID
2. Found -> remove +拼接error(userInfo) ->异步主队列回调failureBlock)
3. 收尾检查,handlers==0 & state == suspend -> taskCancel + removeFromMergedTask
-enqueueMergedTask: - 出队列是firstObject,FIFO -加后面,LIFO -加前面
-dequeueMergedTask - 数组当队列,firstObj + removeObj
AFNetworkActivityIndicatorManager -- 任务数控制�活动器
.h --
各种set + update - 4
- increment/decrementActivityCount - 赋值(手动调用KVO) +更新
.m --
-init - resume/suspend/completeNotification对应方法 -> +-ActivityCount
+sharedManager - init = resume/suspend/completeNotification - 通知方法: networkRequestDidStart&networkRequestDidFinish -- ↓↓↓
-incrementActivityCount & -decrementActivityCount - 赋值(手动调用KVO) +更新
-setEnabled: - =NO -> StateNotActive
-setCurrentState: - NotActive(cancel2+关闭) + DelayingStart(+1s回调Active&NotActive) + Active(cancel1+打开) + DelayingEnd(+0.17回调NotActive)
-updateCurrentStateForNetworkActivityChange: - NotActive(未激活&&有活动=延迟开始) + Active(激活&&没有活动=延迟结束) + DelayingEnd(延迟结束&&有活动=激活)
-startActivationDelayTimer: + activationDelayTimerFired - (定时器1s -> runloop) => (活动数>0 - setState:Active - NotActive) + 活动数>0 - setState:Active - NotActive
-startCompletionDelayTimer: + completionDelayTimerFired - (定时器0.17s -> runloop) => (setState:NotActive) + completion == NotActive
-setNetworkActivityIndicatorVisible: - 赋值(手动调用KVO) + 更新(IndicatorVisible)
UIButton+AFNetworking -- 缓存+下载
.h --
- setImageForState:withURLRequest:placeholderImage:success:failure:
- setBackgroundImageForState:withURLRequest:placeholderImage:success:failure:
.m --
UIButton (_AFNetworking)
af_imageDownloadReceipt - 关联对象 getter & setter(key是各种state)
af_setBackgroundImageDownloadReceipt - 关联对象 getter & setter(key是各种state)
UIButton (AFNetworking)
ImageDownloader- 关联对象 getter & setter
- setImageForState:withURLRequest:placeholderImage:success:failure: -- 缓存+下载
- setBackgroundImageForState:withURLRequest:placeholderImage:success:failure: -- 缓存+下载
UIImageView+AFNetworking -- 缓存+下载
.h --
- setImageWithURLRequest:placeholderImage:success:failure:
.m --
UIImageView (_AFNetworking)
af_activeImageDownloadReceipt - 关联对象 getter & setter
UIImageView (AFNetworking)
sharedImageDownloader - 关联对象 getter & setter
- cancelImageDownloadTask -> cancelTaskForImageDownloadReceipt:(ImageDownloader)
- setImageWithURLRequest:placeholderImage:success:failure: -- 缓存+下载
UIProgressView+AFNetworking -- 根据task数据做相应progress
.h --
-setProgressWithUpload/DownloadProgressOfTask:animated:
.m --
af_uploadProgressAnimated & af_downloadProgressAnimated关联对象
-setProgressWithUploadProgressOfTask:animated: -- (KVO task的"state""countOfBytesSent"属性) + af_setUploadProgressAnimated(保存动画BOOL)
-setProgressWithDownloadProgressOfTask:animated: -- (KVO task的"state""countOfBytesReceived"属性) + af_setDownloadProgressAnimated(保存动画BOOL)
-observeValueForKeyPath:ofObject:change:context: -- (context -> keyPath) -> 异步主队列 - set:比例 animated:af_uploadProgressAnimated OR 异步主队列 - set:比例animated:af_downloadProgressAnimated OR 完成态state -> removeStateObserver + context(对应observer)
UIActivityIndicatorView+AFNetworking -- 任务状态开始结束动画
.h --
- setAnimatingWithStateOfTask:
.m --
UIActivityIndicatorView (AFNetworking) - 持有Observer对象
-af_notificationObserver - notificationObserver懒加载
-setAnimatingWithStateOfTask: -- af_notificationObserver~~
AFActivityIndicatorViewNotificationObserver
-initWithActivityIndicatorView:
-setAnimatingWithStateOfTask: -- (=running->start OR stop) + 通知 - 对应方法↓↓
-af_startAnimating -- 异步主队列startAnimating
-af_stopAnimating -- 异步主队列stopAnimating
UIRefreshControl+AFNetworking
.h --
-setRefreshingWithStateOfTask:
.m --
UIRefreshControl (AFNetworking) - 持有Observer对象
-af_notificationObserver - notificationObserver懒加载
-setAnimatingWithStateOfTask: -- af_notificationObserver~~
AFActivityIndicatorViewNotificationObserver
-initWithActivityIndicatorView:
-setRefreshingWithStateOfTask: -- (=running->start OR stop) + 通知 - 对应方法↓↓
-af_beginRefreshing -- 异步主队列beginRefreshing
-af_endRefreshing -- 异步主队列endRefreshing
UIWebView+AFNetworking
.h --
- loadRequest:progress:success:failure: - ↓↓↓ success: (响应的textEncodingName -> CFStringEncoding -> NSStringEncoding) + (有success前向回调successBlock(response, HTMLString) )
- loadRequest:MIMEType:textEncodingName:progress:success:failure: - (running || suspend -> cancel) + dataTask = (success一直前向回调successBlock + (系统方法loadData + delegate方法) + error一直前向回调failureBlock) + *progress = (taskIdentifier对应delegate.downloadProgress)
.m --
UIWebView (_AFNetworking)
af_URLSessionTask关联对象
UIWebView (AFNetworking)
-sessionManager -- return 关联对象 OR 单例
sessionManager关联对象
-responseSerializer -- return 关联对象 OR 单例
responseSerializer关联对象