AFNetworking2.0源码解析
来源:互联网 发布:淘宝双12报名条件 编辑:程序博客网 时间:2024/05/18 02:55
- #pragma clang diagnostic push
- #pragma clang diagnostic ignored "-Wgnu"
- //code
- #pragma clang diagnostic pop
- static dispatch_queue_t url_request_operation_completion_queue() {
- static dispatch_queue_t af_url_request_operation_completion_queue;
- static dispatch_once_t onceToken;
- dispatch_once(&onceToken, ^{
- af_url_request_operation_completion_queue = dispatch_queue_create("com.alamofire.networking.operation.queue", DISPATCH_QUEUE_CONCURRENT );
- });
- return af_url_request_operation_completion_queue;
- }
- __weak __typeof(self)weakSelf = self;
- self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
- __strong __typeof(weakSelf)strongSelf = weakSelf;
- }];
- NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
- [connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
- [connection start];
- dispatch_group_async(group, queue, ^{
- block();
- });
- dispatch_async(queue, ^{
- dispatch_group_enter(group);
- block()
- dispatch_group_leave(group);
- });
- dispatch_group_async(group, queue, ^{
- [self performBlock:^(){
- block();
- }];
- //未执行到block() group任务就已经完成了
- });
- dispatch_group_enter(group);
- [self performBlock:^(){
- block();
- dispatch_group_leave(group);
- }];
- AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
- NSData *data = [NSKeyedArchiver archivedDataWithRootObject:operation];
- AFHTTPRequestOperation *operationFromDB = [NSKeyedUnarchiver unarchiveObjectWithData:data];
- [operationFromDB start];
- AFURLConnectionOperation.m
- AFHTTPRequestOperation.m
- @{
- @"name" : @"bang",
- @"phone": @{@"mobile": @"xx", @"home": @"xx"},
- @"families": @[@"father", @"mother"],
- @"nums": [NSSet setWithObjects:@"1", @"2", nil]
- }
- ->
- @[
- field: @"name", value: @"bang",
- field: @"phone[mobile]", value: @"xx",
- field: @"phone[home]", value: @"xx",
- field: @"families[]", value: @"father",
- field: @"families[]", value: @"mother",
- field: @"nums", value: @"1",
- field: @"nums", value: @"2",
- ]
- ->
- name=bang&phone[mobile]=xx&phone[home]=xx&families[]=father&families[]=mother&nums=1&num=2
- AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
- NSDictionary *parameters = @{@"foo": @"bar"};
- NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
- [manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id formData) {
- [formData appendPartWithFileURL:filePath name:@"image" error:nil];
- } success:^(AFHTTPRequestOperation *operation, id responseObject) {
- NSLog(@"Success: %@", responseObject);
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
- NSLog(@"Error: %@", error);
- }];
- AFURLRequestSerialization.m
本篇说说安全相关的AFSecurityPolicy模块,AFSecurityPolicy用于验证HTTPS请求的证书,先来看看HTTPS的原理和证书相关的几个问题。
HTTPS
HTTPS连接建立过程大致是,客户端和服务端建立一个连接,服务端返回一个证书,客户端里存有各个受信任的证书机构根证书,用这些根证书对服务端 返回的证书进行验证,经验证如果证书是可信任的,就生成一个pre-master secret,用这个证书的公钥加密后发送给服务端,服务端用私钥解密后得到pre-master secret,再根据某种算法生成master secret,客户端也同样根据这种算法从pre-master secret生成master secret,随后双方的通信都用这个master secret对传输数据进行加密解密。
以上是简单过程,中间还有很多细节,详细过程和原理已经有很多文章阐述得很好,就不再复述,推荐一些相关文章:
关于非对称加密算法的原理:RSA算法原理<一>、<二>
关于整个流程:HTTPS那些事<一>、<二>、<三>
关于数字证书:浅析数字证书
这里说下一开始我比较费解的两个问题:
1.证书是怎样验证的?怎样保证中间人不能伪造证书?
首先要知道非对称加密算法的特点,非对称加密有一对公钥私钥,用公钥加密的数据只能通过对应的私钥解密,用私钥加密的数据只能通过对应的公钥解密。
我们来看最简单的情况:一个证书颁发机构(CA),颁发了一个证书A,服务器用这个证书建立https连接。客户端在信任列表里有这个CA机构的根证书。
首先CA机构颁发的证书A里包含有证书内容F,以及证书加密内容F1,加密内容F1就是用这个证书机构的私钥对内容F加密的结果。(这中间还有一次hash算法,略过。)
建立https连接时,服务端返回证书A给客户端,客户端的系统里的CA机构根证书有这个CA机构的公钥,用这个公钥对证书A的加密内容F1解密得 到F2,跟证书A里内容F对比,若相等就通过验证。整个流程大致是:F->CA私钥加密->F1->客户端CA公钥解密->F。 因为中间人不会有CA机构的私钥,客户端无法通过CA公钥解密,所以伪造的证书肯定无法通过验证。
2.什么是SSL Pinning?
可以理解为证书绑定,是指客户端直接保存服务端的证书,建立https连接时直接对比服务端返回的和客户端保存的两个证书是否一样,一样就表明证书 是真的,不再去系统的信任证书机构里寻找验证。这适用于非浏览器应用,因为浏览器跟很多未知服务端打交道,无法把每个服务端的证书都保存到本地,但CS架 构的像手机APP事先已经知道要进行通信的服务端,可以直接在客户端保存这个服务端的证书用于校验。
为什么直接对比就能保证证书没问题?如果中间人从客户端取出证书,再伪装成服务端跟其他客户端通信,它发送给客户端的这个证书不就能通过验证吗?确 实可以通过验证,但后续的流程走不下去,因为下一步客户端会用证书里的公钥加密,中间人没有这个证书的私钥就解不出内容,也就截获不到数据,这个证书的私 钥只有真正的服务端有,中间人伪造证书主要伪造的是公钥。
为什么要用SSL Pinning?正常的验证方式不够吗?如果服务端的证书是从受信任的的CA机构颁发的,验证是没问题的,但CA机构颁发证书比较昂贵,小企业或个人用户 可能会选择自己颁发证书,这样就无法通过系统受信任的CA机构列表验证这个证书的真伪了,所以需要SSL Pinning这样的方式去验证。
AFSecurityPolicy
NSURLConnection已经封装了https连接的建立、数据的加密解密功能,我们直接使用NSURLConnection是可以访问 https网站的,但NSURLConnection并没有验证证书是否合法,无法避免中间人攻击。要做到真正安全通讯,需要我们手动去验证服务端返回的 证书,AFSecurityPolicy封装了证书验证的过程,让用户可以轻易使用,除了去系统信任CA机构列表验证,还支持SSL Pinning方式的验证。使用方法:
//把服务端证书(需要转换成cer格式)放到APP项目资源里,AFSecurityPolicy会自动寻找根目录下所有cer文件
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];
securityPolicy.allowInvalidCertificates = YES;
[AFHTTPRequestOperationManager manager].securityPolicy = securityPolicy;
[manager GET:@
"https://example.com/"
parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
AFSecurityPolicy分三种验证模式:
AFSSLPinningModeNone
这个模式表示不做SSL pinning,只跟浏览器一样在系统的信任机构列表里验证服务端返回的证书。若证书是信任机构签发的就会通过,若是自己服务器生成的证书,这里是不会通过的。
AFSSLPinningModeCertificate
这个模式表示用证书绑定方式验证证书,需要客户端保存有服务端的证书拷贝,这里验证分两步,第一步验证证书的域名/有效期等信息,第二步是对比服务端返回的证书跟客户端返回的是否一致。
这里还没弄明白第一步的验证是怎么进行的,代码上跟去系统信任机构列表里验证一样调用了SecTrustEvaluate,只是这里的列表换成了客户端保存的那些证书列表。若要验证这个,是否应该把服务端证书的颁发机构根证书也放到客户端里?
AFSSLPinningModePublicKey
这个模式同样是用证书绑定方式验证,客户端要有服务端的证书拷贝,只是验证时只验证证书里的公钥,不验证证书的有效期等信息。只要公钥是正确的,就能保证通信不会被窃听,因为中间人没有私钥,无法解开通过公钥加密的数据。
整个AFSecurityPolicy就是实现这这几种验证方式,剩下的就是实现细节了,详见源码。
// AFSecurity.m
//
// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFSecurityPolicy.h"
// Equivalent of macro in , without causing compiler warning:
// "'DebugAssert' is deprecated: first deprecated in OS X 10.8"
//这两个宏方法用于方便地处理调用各种证书方法过程中出现的错误,出现错误后用goto语句直接跳转到结束语
//关于为什么要用 __builtin_expect (x, 0) 而不直接用 x != 0,是为了CPU执行时的性能优化,见这里:
//http://stackoverflow.com/questions/7346929/why-do-we-use-builtin-expect-when-a-straightforward-way-is-to-use-if-else
#ifndef AF_Require
#define AF_Require(assertion, exceptionLabel) \
do
{ \
if
(__builtin_expect(!(assertion), 0)) { \
goto exceptionLabel; \
} \
}
while
(0)
#endif
#ifndef AF_Require_noErr
#define AF_Require_noErr(errorCode, exceptionLabel) \
do
{ \
if
(__builtin_expect(0 != (errorCode), 0)) { \
goto exceptionLabel; \
} \
}
while
(0)
#endif
#if !defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
static NSData * AFSecKeyGetData(SecKeyRef key) {
CFDataRef data = NULL;
AF_Require_noErr(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out);
return
(__bridge_transfer NSData *)data;
_out:
if
(data) {
CFRelease(data);
}
return
nil;
}
#endif
static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
return
[(__bridge id)key1 isEqual:(__bridge id)key2];
#else
return
[AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)];
#endif
}
//从证书里取public key
static id AFPublicKeyForCertificate(NSData *certificate) {
id allowedPublicKey = nil;
SecCertificateRef allowedCertificate;
SecCertificateRef allowedCertificates[1];
CFArrayRef tempCertificates = nil;
SecPolicyRef policy = nil;
SecTrustRef allowedTrust = nil;
SecTrustResultType result;
//取证书SecCertificateRef -> 生成证书数组 -> 生成SecTrustRef -> 从SecTrustRef取PublicKey
allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
AF_Require(allowedCertificate != NULL, _out);
allowedCertificates[0] = allowedCertificate;
tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);
policy = SecPolicyCreateBasicX509();
AF_Require_noErr(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out);
AF_Require_noErr(SecTrustEvaluate(allowedTrust, &result), _out);
allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);
_out:
if
(allowedTrust) {
CFRelease(allowedTrust);
}
if
(policy) {
CFRelease(policy);
}
if
(tempCertificates) {
CFRelease(tempCertificates);
}
if
(allowedCertificate) {
CFRelease(allowedCertificate);
}
return
allowedPublicKey;
}
static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
BOOL isValid = NO;
SecTrustResultType result;
AF_Require_noErr(SecTrustEvaluate(serverTrust, &result), _out);
//kSecTrustResultUnspecified:证书通过验证,但用户没有设置这些证书是否被信任
//kSecTrustResultProceed:证书通过验证,用户有操作设置了证书被信任,例如在弹出的是否信任的alert框中选择always trust
isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
_out:
return
isValid;
}
//取出服务端返回的所有证书
static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) {
CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
for
(CFIndex i = 0; i < certificateCount; i++) {
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
[trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
}
return
[NSArray arrayWithArray:trustChain];
}
//取出服务端返回证书里所有的public key
static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
SecPolicyRef policy = SecPolicyCreateBasicX509();
CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
for
(CFIndex i = 0; i 生成证书数组 -> 生成SecTrustRef -> 从SecTrustRef取PublicKey
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
SecCertificateRef someCertificates[] = {certificate};
CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
SecTrustRef trust;
AF_Require_noErr(SecTrustCreateWithCertificates(certificates, policy, &trust), _out);
SecTrustResultType result;
AF_Require_noErr(SecTrustEvaluate(trust, &result), _out);
[trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
_out:
if
(trust) {
CFRelease(trust);
}
if
(certificates) {
CFRelease(certificates);
}
continue
;
}
CFRelease(policy);
return
[NSArray arrayWithArray:trustChain];
}
#pragma mark -
@interface AFSecurityPolicy()
@property (readwrite, nonatomic, strong) NSArray *pinnedPublicKeys;
@end
@implementation AFSecurityPolicy
+ (NSArray *)defaultPinnedCertificates {
//默认证书列表,遍历根目录下所有.cer文件
static NSArray *_defaultPinnedCertificates = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSArray *paths = [bundle pathsForResourcesOfType:@
"cer"
inDirectory:@
"."
];
NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]];
for
(NSString *path
in
paths) {
NSData *certificateData = [NSData dataWithContentsOfFile:path];
[certificates addObject:certificateData];
}
_defaultPinnedCertificates = [[NSArray alloc] initWithArray:certificates];
});
return
_defaultPinnedCertificates;
}
+ (instancetype)defaultPolicy {
AFSecurityPolicy *securityPolicy = [[self alloc] init];
securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
return
securityPolicy;
}
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode {
AFSecurityPolicy *securityPolicy = [[self alloc] init];
securityPolicy.SSLPinningMode = pinningMode;
securityPolicy.validatesDomainName = YES;
[securityPolicy setPinnedCertificates:[self defaultPinnedCertificates]];
return
securityPolicy;
}
- (id)init {
self = [
super
init];
if
(!self) {
return
nil;
}
self.validatesCertificateChain = YES;
return
self;
}
#pragma mark -
- (void)setPinnedCertificates:(NSArray *)pinnedCertificates {
_pinnedCertificates = pinnedCertificates;
if
(self.pinnedCertificates) {
//预先取出public key,用于AFSSLPinningModePublicKey方式的验证
NSMutableArray *mutablePinnedPublicKeys = [NSMutableArray arrayWithCapacity:[self.pinnedCertificates count]];
for
(NSData *certificate
in
self.pinnedCertificates) {
id publicKey = AFPublicKeyForCertificate(certificate);
if
(!publicKey) {
continue
;
}
[mutablePinnedPublicKeys addObject:publicKey];
}
self.pinnedPublicKeys = [NSArray arrayWithArray:mutablePinnedPublicKeys];
}
else
{
self.pinnedPublicKeys = nil;
}
}
#pragma mark -
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust {
return
[self evaluateServerTrust:serverTrust forDomain:nil];
}
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
forDomain:(NSString *)domain
{
NSMutableArray *policies = [NSMutableArray array];
if
(self.validatesDomainName) {
[policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(
true
, (__bridge CFStringRef)domain)];
}
else
{
[policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
}
SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
//向系统内置的根证书验证服务端返回的证书是否合法
//若使用自签名证书,这里的验证是会不合法的,需要设allowInvalidCertificates = YES
if
(!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) {
return
NO;
}
//取出服务端返回的证书
NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust);
switch
(self.SSLPinningMode) {
case
AFSSLPinningModeNone:
//两种情况走到这里,
//一是通过系统证书验证,返回认证成功
//二是没通过验证,但allowInvalidCertificates = YES,也就是说完全不认证直接返回认证成功
return
YES;
//验证整个证书
case
AFSSLPinningModeCertificate: {
NSMutableArray *pinnedCertificates = [NSMutableArray array];
for
(NSData *certificateData
in
self.pinnedCertificates) {
[pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)];
}
//在本地证书里验证服务端返回的证书的有效性
SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates);
if
(!AFServerTrustIsValid(serverTrust)) {
return
NO;
}
if
(!self.validatesCertificateChain) {
return
YES;
}
//整个证书链都跟本地的证书匹配才给过
NSUInteger trustedCertificateCount = 0;
for
(NSData *trustChainCertificate
in
serverCertificates) {
if
([self.pinnedCertificates containsObject:trustChainCertificate]) {
trustedCertificateCount++;
}
}
return
trustedCertificateCount == [serverCertificates count];
}
//只验证证书的public key
case
AFSSLPinningModePublicKey: {
NSUInteger trustedPublicKeyCount = 0;
NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust);
//如果不用验证整个证书链,取第一个也就是真正会使用的那个证书验证就行
if
(!self.validatesCertificateChain && [publicKeys count] > 0) {
publicKeys = @[[publicKeys firstObject]];
}
//在本地证书里搜索相等的public key,记录找到个数
for
(id trustChainPublicKey
in
publicKeys) {
for
(id pinnedPublicKey
in
self.pinnedPublicKeys) {
if
(AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
trustedPublicKeyCount += 1;
}
}
}
//验证整个证书链的情况:每个public key都在本地找到算验证通过
//验证单个证书的情况:找到一个算验证通过
return
trustedPublicKeyCount > 0 && ((self.validatesCertificateChain && trustedPublicKeyCount == [serverCertificates count]) || (!self.validatesCertificateChain && trustedPublicKeyCount >= 1));
}
}
return
NO;
}
#pragma mark - NSKeyValueObserving
+ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys {
return
[NSSet setWithObject:@
"pinnedCertificates"
];
}
@end
结构
AFURLResponseSerialization负责解析网络返回数据,检查数据是否合法,把NSData数据转成相应的对象,内置的转换器有json,xml,plist,image,用户可以很方便地继承基类AFHTTPResponseSerializer去解析更多的数据格式,AFNetworking这一套响应解析机制结构很简单,主要就是两个方法:
1.-validateResponse:data:error:
基类AFHTTPResponseSerializer的这个方法检测返回的HTTP状态码和数据类型是否合法,属性acceptableStatusCodes和acceptableContentTypes规定了合法的状态码和数据类型,例如JSONSerialization就把acceptableContentTypes设为@”application/json”, @”text/json”, @”text/javascript”,若不是这三者之一,就验证失败,返回相应的NSError对象。一般子类不需要重写这个方法,只需要设置好acceptableStatusCodes和acceptableContentTypes就行了。
2.-responseObjectForResponse:data:error:
这个方法解析数据,把NSData转成相应的对象,上层AFURLConnectionOperation会调用这个方法获取转换后的对象。
在解析数据之前会先调上述的validateResponse方法检测HTTP响应是否合法,要注意的是即使这里检测返回不合法,也会继续解析数据生成对象,因为有可能错误信息就在返回的数据里。
如果validateResponse返回error,这里的解析数据又出错,这时有两个error对象,怎样返回给上层?这里的处理是把解析数据的NSError对象保存到validateResponse NSError的userInfo里,作为UnderlyingError,NSError专门给了个NSUnderlyingErrorKey作为这种错误包含错误的键值。
剩下的就是NSecureCoding相关方法了,如果子类增加了property,需要加上相应的NSecureCoding方法。
JSON解析
AFJSONResponseSerializer使用系统内置的NSJSONSerialization解析json,NSJSON只支持解析UTF8编码的数据(还有UTF-16LE之类的,都不常用),所以要先把返回的数据转成UTF8格式。这里会尝试用HTTP返回的编码类型和自己设置的stringEncoding去把数据解码转成字符串NSString,再把NSString用UTF8编码转成NSData,再用NSJSONSerialization解析成对象返回。
上述过程是NSData->NSString->NSData->NSObject,这里有个问题,如果你能确定服务端返回的是UTF8编码的json数据,那NSData->NSString->NSData这两步就是无意义的,而且这两步进行了两次编解码,很浪费性能,所以如果确定服务端返回utf8编码数据,就建议自己再写个JSONResponseSerializer,跳过这两个步骤。
此外AFJSONResponseSerializer专门写了个方法去除NSNull,直接把对象里值是NSNull的键去掉,还蛮贴心,若不去掉,上层很容易忽略了这个数据类型,判断了数据是否nil没判断是否NSNull,进行了错误的调用导致core。
图片解压
当我们调用UIImage的方法imageWithData:方法把数据转成UIImage对象后,其实这时UIImage对象还没准备好需要渲染到屏幕的数据,现在的网络图像PNG和JPG都是压缩格式,需要把它们解压转成bitmap后才能渲染到屏幕上,如果不做任何处理,当你把UIImage赋给UIImageView,在渲染之前底层会判断到UIImage对象未解压,没有bitmap数据,这时会在主线程对图片进行解压操作,再渲染到屏幕上。这个解压操作是比较耗时的,如果任由它在主线程做,可能会导致速度慢UI卡顿的问题。
AFImageResponseSerializer除了把返回数据解析成UIImage外,还会把图像数据解压,这个处理是在子线程(AFNetworking专用的一条线程,详见AFURLConnectionOperation),处理后上层使用返回的UIImage在主线程渲染时就不需要做解压这步操作,主线程减轻了负担,减少了UI卡顿问题。
具体实现上在AFInflatedImageFromResponseWithDataAtScale里,创建一个画布,把UIImage画在画布上,再把这个画布保存成UIImage返回给上层。只有JPG和PNG才会尝试去做解压操作,期间如果解压失败,或者遇到CMKY颜色格式的jpg,或者图像太大(解压后的bitmap太占内存,一个像素3-4字节,搞不好内存就爆掉了),就直接返回未解压的图像。
另外在代码里看到iOS才需要这样手动解压,MacOS上已经有封装好的对象NSBitmapImageRep可以做这个事。
关于图片解压,还有几个问题不清楚:
1.本来以为调用imageWithData方法只是持有了数据,没有做解压相关的事,后来看到调用堆栈发现已经做了一些解压操作,从调用名字看进行了huffman解码,不知还会继续做到解码jpg的哪一步。
2.以上图片手动解压方式都是在CPU进行的,如果不进行手动解压,把图片放进layer里,让底层自动做这个事,是会用GPU进行的解压的。不知用GPU解压与用CPU解压速度会差多少,如果GPU速度很快,就算是在主线程做解压,也变得可以接受了,就不需要手动解压这样的优化了,不过目前没找到方法检测GPU解压的速度。
P.S. 关于图片解压,有篇挺挺不错的文章:Avoiding Image Decompression Sickness
源码注释
AFURLResponseSerialization.m
AFNetworking使用总结
- 分享类型:游戏开发相关
2 添加类库 Security.framework、MobileCoreServices.framework、SystemConfiguration.framework
3 在使用的地方 #import "AFNetworking.h"
解决编译时警告:
Prefix.pch文件中加入
#import <SystemConfiguration/SystemConfiguration.h>
#import <MobileCoreServices/MobileCoreServices.h>
注:AFNetWorking使用了ARC ,在不使用ARC项目中使用时,对AFNetWorking的所有.m文件添加“-fobjc-arc”
在使用ARC项目中,使用“不使用ARC”的类库时,对类库的.m文件添加“-fno-objc-arc”
static NSString*const BaseURLString = @"http://www.raywenderlich.com/downloads/weather_sample/"; // 1 NSString *weatherUrl = [NSStringstringWithFormat:@"%@weather.php?format=json",BaseURLString]; NSURL *url = [NSURLURLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequestrequestWithURL:url]
// 2 AFJSONRequestOperation *operation = [AFJSONRequestOperationJSONRequestOperationWithRequest:request success:^(NSURLRequest*request, NSHTTPURLResponse *response, id JSON) { // NSDictionary*dicWeather = (NSDictionary *)JSON; NSLog(@"result:%@",dicWeather); } failure:^(NSURLRequest*request, NSHTTPURLResponse *response, NSError *error, id JSON) { UIAlertView*alertView = [[UIAlertView alloc] initWithTitle:@"Error RetrievingWeather" message:[NSStringstringWithFormat:@"%@",error] delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil]; [alertView show]; }];
// 5 [operation start];
- (1)根据基本的URL构造除完整的一个URL,然后通过这个完整的URL获得一个NSURL对象,然后根据这个url获得一个NSURLRequest。
- NSMutableURLRequest *request = [client requestWithMethod:@"GET" path:@"/" parameters:nil];//这里的parameters:参数就是你的第二个问题如何设置参数
- [request setTimeoutInterval:120];
- AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:^{...} failure:^{...}];
- [client enqueueHTTPRequestOperation:operation];
- - (NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters{
- NSMutableURLRequest *request = [super requestWithMethod:method path:path parameters:parameters];
- [request setTimeoutInterval:15];
- return request; }
- [self postPath:@"" parameters:nil //参数
- success:^(AFHTTPRequestOperation *operation, id responseObject) {
- if (success) {
- success((AFJSONRequestOperation *)operation, responseObject);
- }
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
- if (failure) {
- failure((AFJSONRequestOperation *)operation, error);
- }
- }];
(2)AFJSONRequestOperation是一个完整的类,整合了从网络中获取数据并对JSON进行解析。
(3)当请求成功,则运行成功块。在本例中,把解析出来的天气数据从JSON变量转换为一个字典(dictionary),并将其存储在字典中。
(4)如果运行出问题了,则运行失败块(failure block),比如网络不可用。如果failure block被调用了,将会通过提示框显示错误信息。
6.AFNetWorking异步加载图片
#import “UIImageView+AFNetworking.h”
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(40, 80, 40, 40)];
__weak UIImageView *_imageView = imageView;
[imageView setImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURLURLWithString:@"http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"]] placeholderImage:[UIImage imageNamed:@"placeholder.png"] success:^(NSURLRequest *request,NSHTTPURLResponse *response, UIImage *image){ _imageView.image = image; [_imageView setNeedsDisplay]; } failure:^(NSURLRequest *request, NSHTTPURLResponse*response, NSError *error){ ; }];
[self.view addSubview:imageView];
7.GET 和POST请求
(1).构建一个baseURL,以及一个参数字典,并将这两个变量传给AFHTTPClient.
(2).将AFJSONRequestOperation注册为HTTP的操作, 这样就可以跟之前的示例一样,可以获得解析好的JSON数据。
(3).做了一个GET请求,这个请求有一对block:success和failure。
(4).POST请求跟GET一样
<pre name="code" class="objc">AFHTTPClient *client= [[AFHTTPClient alloc] initWithBaseURL:baseURL];[clientregisterHTTPOperationClass:[AFJSONRequestOperation class]]; [clientsetDefaultHeader:@"Accept" value:@"application/json"]; [client postPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { self.weather =responseObject; self.title = @"HTTPPOST"; [self.tableViewreloadData]; } failure:^(AFHTTPRequestOperation *operation, NSError*error) { UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather" message:[NSStringstringWithFormat:@"%@",error] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [av show]; } ]; [client getPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather" message:[NSStringstringWithFormat:@"%@",error] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [av show]; } ];另外,请求方式可以创建一个类继承AFHTTPClient ,官方的例子就是这样写的。
状态栏设置
在Appdelegate里面的 - (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法中添加 [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];用来给用户做出网络访问的提示。
请求超时设置
timeout和参数都是在NSURLRequest/NSMutableURLRequest设置的
如果你是继承了AFHTTPClient
就需要override一个方法requestWithMethod
复制代码
这个时候的参数设置是调用
复制代码
- AFNetworking2.0源码解析
- AFNetworking2.0源码解析
- AFNetworking2.0源码解析
- AFNetworking2.0源码解析
- AFNetworking2.0源码解析
- AFNetworking2.0源码解析
- AFNetworking2.0源码解析
- AFNetworking2.0源码解析
- AFNetworking2.0源码解析
- AFNetworking2.0源码解析
- afnetworking2.0源码解析
- AFNetworking2.0源码解析<一>
- AFNetworking2.0的源码解析
- AFNetworking2.0源码解析<一>
- AFNetworking2.0源码解析<一>
- AFNetworking2.0源码解析<二>
- AFNetworking2.0源码解析<二>
- AFNetworking2.0源码解析<二>
- Unity3D学习笔记之四完善Prefab并添加First Person Controller
- Python个人代码库: GPI模块编写
- 使用NSSecureCoding协议进行对象编解码
- 关于PAT Basic Level 1013题的感想
- PAT A1025 PAT Ranking
- AFNetworking2.0源码解析
- 解决键盘遮挡输入框(UITextField)问题
- Number Sequence - UVa 10706
- android开发即时刷新某路径下的文件
- LeetCode_Search in Rotated Sorted Array II
- 向有序循环单向链表中插入节点
- QQ5.0主界面实现
- 6-17复数四则运算
- sqlldr提交两次,数据类型报错