Commit 88ce850a by 徐利超

update

parent 509c1dfa
...@@ -15,7 +15,9 @@ ...@@ -15,7 +15,9 @@
#import "YUNXINDemoViewController.h" #import "YUNXINDemoViewController.h"
#import <CommonCrypto/CommonCryptor.h> #import <CommonCrypto/CommonCryptor.h>
#import "CHNetworkingManager.h" #import "CHNetworkingManager.h"
#import <AFJSONRPCClient/AFJSONRPCClient.h>
#import <AFNetworking/AFHTTPRequestOperationManager.h>
static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@interface LoginViewController () @interface LoginViewController ()
...@@ -196,8 +198,8 @@ static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopq ...@@ -196,8 +198,8 @@ static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopq
// vc.otherUid = self.otherUid; // vc.otherUid = self.otherUid;
// vc.modalPresentationStyle = UIModalPresentationFullScreen; // vc.modalPresentationStyle = UIModalPresentationFullScreen;
// [self presentViewController:vc animated:YES completion:nil]; // [self presentViewController:vc animated:YES completion:nil];
// [self sendASRNLPReq]; [self sendASRNLPReq];
[self TTSSessionBegin]; // [self TTSSessionBegin];
} }
...@@ -219,9 +221,9 @@ static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopq ...@@ -219,9 +221,9 @@ static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopq
@"account":@"50006" @"account":@"50006"
}; };
[[CHNetworkingManager new] httpRequsetForUploadFile:data param:dic onSuccessBlock:^(NSDictionary *dic) { [[CHNetworkingManager new] httpRequsetForUploadFile:data param:dic onSuccessBlock:^(NSDictionary *dic) {
NSLog(@"===>>> asr,nlp success:%@",dic);
} failureBlock:^(NSError *error) { } failureBlock:^(NSError *error) {
NSLog(@"===>>> asr,nlp error:%@",error.domain);
}]; }];
} }
...@@ -251,11 +253,21 @@ static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopq ...@@ -251,11 +253,21 @@ static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopq
}; };
NSDictionary *sendDic = [self getSendJsonWithCmd:1 param:param]; NSDictionary *sendDic = [self getSendJsonWithCmd:1 param:param];
[[CHNetworkingManager new] requestJsonStringPOSTWithParameter:[self dictionaryToJSONString:sendDic] successBlock:^(NSDictionary *dic) { AFJSONRPCClient *client = [AFJSONRPCClient clientWithEndpointURL:[NSURL URLWithString:@"http://fhts.test.bank.ecitic.com/voicePre/portal/tts"]];
NSLog(@"===>>> tts:ssb success:%@",dic); if (client) {
} failureBlock:^(NSError *error) { [client invokeMethod:@"" withParameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"===>>> tts:ssb error:%@", error.domain); NSLog(@"===>>> tts:ssb success:%@",responseObject);
}]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"===>>> tts:ssb error:%@",error.userInfo);
}];
}else {
NSLog(@"client uninit");
}
// [[CHNetworkingManager new] requestJsonStringPOSTWithParameter:[self dictionaryToJSONString:sendDic] successBlock:^(NSDictionary *dic) {
// NSLog(@"===>>> tts:ssb success:%@",dic);
// } failureBlock:^(NSError *error) {
// NSLog(@"===>>> tts:ssb error:%@", error.domain);
// }];
} }
......
...@@ -69,7 +69,7 @@ typedef enum : NSUInteger { ...@@ -69,7 +69,7 @@ typedef enum : NSUInteger {
switch (method) { switch (method) {
case GET:{ case GET:{
[self GET:url parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { [self GET:url parameters:param success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(responseObject); success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if(self.count == 0) { if(self.count == 0) {
...@@ -85,7 +85,7 @@ typedef enum : NSUInteger { ...@@ -85,7 +85,7 @@ typedef enum : NSUInteger {
break; break;
} }
case POST:{ case POST:{
[self POST:url parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { [self POST:url parameters:param success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(responseObject); success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if(self.count == 0) { if(self.count == 0) {
...@@ -170,13 +170,16 @@ typedef enum : NSUInteger { ...@@ -170,13 +170,16 @@ typedef enum : NSUInteger {
[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { NSURLSessionTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) { if (error) {
failure(error); failure(error);
}else { }else {
success(responseObject); success(responseObject);
} }
}]; }];
// NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
//
// }];
[dataTask resume]; [dataTask resume];
} }
...@@ -195,7 +198,6 @@ typedef enum : NSUInteger { ...@@ -195,7 +198,6 @@ typedef enum : NSUInteger {
// [self.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"device"]; // [self.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"device"];
// [self.requestSerializer setValue:[CHVersionTool getBundleShortVersionString] forHTTPHeaderField:@"version"]; // [self.requestSerializer setValue:[CHVersionTool getBundleShortVersionString] forHTTPHeaderField:@"version"];
[self POST:url parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { [self POST:url parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
if (data) { if (data) {
// 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名 // 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名
// 要解决此问题, // 要解决此问题,
...@@ -208,14 +210,34 @@ typedef enum : NSUInteger { ...@@ -208,14 +210,34 @@ typedef enum : NSUInteger {
[formData appendPartWithFileData:data name:dataName fileName:fileName mimeType:@"pcm"]; [formData appendPartWithFileData:data name:dataName fileName:fileName mimeType:@"pcm"];
} }
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(responseObject); success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error); failure(error);
}]; }];
// [self POST:url parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//
// if (data) {
// // 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名
// // 要解决此问题,
// // 可以在上传时使用当前的系统时间作为文件名
// NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// // 设置时间格式
// formatter.dateFormat = @"yyyyMMddHHmmss";
// NSString *str = [formatter stringFromDate:[NSDate date]];
// NSString *fileName = [NSString stringWithFormat:@"%@.pcm", str];
//
// [formData appendPartWithFileData:data name:dataName fileName:fileName mimeType:@"pcm"];
// }
//
// } progress:^(NSProgress * _Nonnull uploadProgress) {
//
// } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
// success(responseObject);
// } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// failure(error);
// }];
} }
- (CHNetWorkStatus)isNetWorkEnable { - (CHNetWorkStatus)isNetWorkEnable {
......
...@@ -51,7 +51,7 @@ ...@@ -51,7 +51,7 @@
failureBlock:(RequestFailureInfoBlock)failure failureBlock:(RequestFailureInfoBlock)failure
{ {
TraceS(@"=====>>>> func:%@",func); TraceS(@"=====>>>> func:%@",func);
NSString *mainUrl = @"http://192.168.60.72:8080"; NSString *mainUrl = @"http://192.168.43.142:8080";
[[CHNetworkingRequest sharedClient] requestformDataWithPath:mainUrl functionName:func param:param data:data dataName:dataName successBlock:^(NSDictionary *dic) { [[CHNetworkingRequest sharedClient] requestformDataWithPath:mainUrl functionName:func param:param data:data dataName:dataName successBlock:^(NSDictionary *dic) {
success(dic); success(dic);
} failureBlock:^(NSDictionary *dic, NSError *error) { } failureBlock:^(NSDictionary *dic, NSError *error) {
......
PODS: PODS:
- AFNetworking (3.2.1): - AFJSONRPCClient (2.1.1):
- AFNetworking/NSURLSession (= 3.2.1) - AFNetworking (~> 2.1)
- AFNetworking/Reachability (= 3.2.1) - AFNetworking (2.7.0):
- AFNetworking/Security (= 3.2.1) - AFNetworking/NSURLConnection (= 2.7.0)
- AFNetworking/Serialization (= 3.2.1) - AFNetworking/NSURLSession (= 2.7.0)
- AFNetworking/UIKit (= 3.2.1) - AFNetworking/Reachability (= 2.7.0)
- AFNetworking/NSURLSession (3.2.1): - AFNetworking/Security (= 2.7.0)
- AFNetworking/Serialization (= 2.7.0)
- AFNetworking/UIKit (= 2.7.0)
- AFNetworking/NSURLConnection (2.7.0):
- AFNetworking/Reachability - AFNetworking/Reachability
- AFNetworking/Security - AFNetworking/Security
- AFNetworking/Serialization - AFNetworking/Serialization
- AFNetworking/Reachability (3.2.1) - AFNetworking/NSURLSession (2.7.0):
- AFNetworking/Security (3.2.1) - AFNetworking/Reachability
- AFNetworking/Serialization (3.2.1) - AFNetworking/Security
- AFNetworking/UIKit (3.2.1): - AFNetworking/Serialization
- AFNetworking/Reachability (2.7.0)
- AFNetworking/Security (2.7.0)
- AFNetworking/Serialization (2.7.0)
- AFNetworking/UIKit (2.7.0):
- AFNetworking/NSURLConnection
- AFNetworking/NSURLSession - AFNetworking/NSURLSession
- IQKeyboardManager (6.5.6) - IQKeyboardManager (6.5.6)
- Masonry (1.1.0) - Masonry (1.1.0)
DEPENDENCIES: DEPENDENCIES:
- AFJSONRPCClient
- AFNetworking - AFNetworking
- IQKeyboardManager - IQKeyboardManager
- Masonry - Masonry
SPEC REPOS: SPEC REPOS:
https://github.com/CocoaPods/Specs.git: https://github.com/CocoaPods/Specs.git:
- AFJSONRPCClient
- AFNetworking - AFNetworking
- IQKeyboardManager - IQKeyboardManager
- Masonry - Masonry
SPEC CHECKSUMS: SPEC CHECKSUMS:
AFNetworking: b6f891fdfaed196b46c7a83cf209e09697b94057 AFJSONRPCClient: 333bada91e6e45398446b8bd84e238e6f2389b1b
AFNetworking: 8dd5f9b9691e09186393069a12cc3b5ed7c8b511
IQKeyboardManager: 2a6e97afdafc7becf0cb17a9a8d795e3a980717f IQKeyboardManager: 2a6e97afdafc7becf0cb17a9a8d795e3a980717f
Masonry: 678fab65091a9290e40e2832a55e7ab731aad201 Masonry: 678fab65091a9290e40e2832a55e7ab731aad201
PODFILE CHECKSUM: 05dc85bcfeedc8253c411e67a7ee98c5ff6bdd07 PODFILE CHECKSUM: c17dd2b51db38ebc1361046f88ac3934293eb4ef
COCOAPODS: 1.8.3 COCOAPODS: 1.8.3
// AFJSONRPCClient.m
//
// Created by wiistriker@gmail.com
// Copyright (c) 2013 JustCommunication
//
// 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 <AFNetworking/AFHTTPRequestOperationManager.h>
/**
AFJSONRPCClient objects communicate with web services using the JSON-RPC 2.0 protocol.
@see http://www.jsonrpc.org/specification
*/
@interface AFJSONRPCClient : AFHTTPRequestOperationManager
/**
The endpoint URL for the webservice.
*/
@property (readonly, nonatomic, strong) NSURL *endpointURL;
/**
Creates and initializes a JSON-RPC client with the specified endpoint.
@param URL The endpoint URL.
@return An initialized JSON-RPC client.
*/
+ (instancetype)clientWithEndpointURL:(NSURL *)URL;
/**
Initializes a JSON-RPC client with the specified endpoint.
@param URL The endpoint URL.
@return An initialized JSON-RPC client.
*/
- (id)initWithEndpointURL:(NSURL *)URL;
/**
Creates a request with the specified HTTP method, parameters, and request ID.
@param method The HTTP method. Must not be `nil`.
@param parameters The parameters to encode into the request. Must be either an `NSDictionary` or `NSArray`.
@param requestId The ID of the request.
@return A JSON-RPC-encoded request.
*/
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
parameters:(id)parameters
requestId:(id)requestId;
/**
Creates a request with the specified method, and enqueues a request operation for it.
@param method The HTTP method. Must not be `nil`.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
*/
- (void)invokeMethod:(NSString *)method
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates a request with the specified method and parameters, and enqueues a request operation for it.
@param method The HTTP method. Must not be `nil`.
@param parameters The parameters to encode into the request. Must be either an `NSDictionary` or `NSArray`.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
*/
- (void)invokeMethod:(NSString *)method
withParameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates a request with the specified method and parameters, and enqueues a request operation for it.
@param method The HTTP method. Must not be `nil`.
@param parameters The parameters to encode into the request. Must be either an `NSDictionary` or `NSArray`.
@param requestId The ID of the request.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
*/
- (void)invokeMethod:(NSString *)method
withParameters:(id)parameters
requestId:(id)requestId
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
///----------------------
/// @name Method Proxying
///----------------------
/**
Returns a JSON-RPC client proxy object with methods conforming to the specified protocol.
@param protocol The protocol.
@discussion This approach allows Objective-C messages to be transparently forwarded as JSON-RPC calls.
*/
- (id)proxyWithProtocol:(Protocol *)protocol;
@end
///----------------
/// @name Constants
///----------------
/**
AFJSONRPCClient errors.
*/
extern NSString * const AFJSONRPCErrorDomain;
// AFJSONRPCClient.m
//
// Created by wiistriker@gmail.com
// Copyright (c) 2013 JustCommunication
//
// 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 "AFJSONRPCClient.h"
#import "AFHTTPRequestOperation.h"
#import <objc/runtime.h>
NSString * const AFJSONRPCErrorDomain = @"com.alamofire.networking.json-rpc";
static NSString * AFJSONRPCLocalizedErrorMessageForCode(NSInteger code) {
switch(code) {
case -32700:
return @"Parse Error";
case -32600:
return @"Invalid Request";
case -32601:
return @"Method Not Found";
case -32602:
return @"Invalid Params";
case -32603:
return @"Internal Error";
default:
return @"Server Error";
}
}
@interface AFJSONRPCProxy : NSProxy
- (id)initWithClient:(AFJSONRPCClient *)client
protocol:(Protocol *)protocol;
@end
#pragma mark -
@interface AFJSONRPCClient ()
@property (readwrite, nonatomic, strong) NSURL *endpointURL;
@end
@implementation AFJSONRPCClient
+ (instancetype)clientWithEndpointURL:(NSURL *)URL {
return [[self alloc] initWithEndpointURL:URL];
}
- (id)initWithEndpointURL:(NSURL *)URL {
NSParameterAssert(URL);
self = [super initWithBaseURL:URL];
if (!self) {
return nil;
}
self.requestSerializer = [AFJSONRequestSerializer serializer];
[self.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"application/json-rpc", @"application/jsonrequest", nil];
self.endpointURL = URL;
return self;
}
- (void)invokeMethod:(NSString *)method
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
[self invokeMethod:method withParameters:@[] success:success failure:failure];
}
- (void)invokeMethod:(NSString *)method
withParameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
[self invokeMethod:method withParameters:parameters requestId:@(1) success:success failure:failure];
}
- (void)invokeMethod:(NSString *)method
withParameters:(id)parameters
requestId:(id)requestId
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
NSMutableURLRequest *request = [self requestWithMethod:method parameters:parameters requestId:requestId];
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
[self.operationQueue addOperation:operation];
}
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
parameters:(id)parameters
requestId:(id)requestId
{
NSParameterAssert(method);
if (!parameters) {
parameters = @[];
}
NSAssert([parameters isKindOfClass:[NSDictionary class]] || [parameters isKindOfClass:[NSArray class]], @"Expect NSArray or NSDictionary in JSONRPC parameters");
if (!requestId) {
requestId = @(1);
}
NSMutableDictionary *payload = [NSMutableDictionary dictionary];
payload[@"jsonrpc"] = @"2.0";
payload[@"method"] = method;
payload[@"params"] = parameters;
payload[@"id"] = [requestId description];
return [self.requestSerializer requestWithMethod:@"POST" URLString:[self.endpointURL absoluteString] parameters:payload error:nil];
}
#pragma mark - AFHTTPClient
- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
return [super HTTPRequestOperationWithRequest:urlRequest success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSInteger code = 0;
NSString *message = nil;
id data = nil;
if ([responseObject isKindOfClass:[NSDictionary class]]) {
id result = responseObject[@"result"];
id error = responseObject[@"error"];
if (result && result != [NSNull null]) {
if (success) {
success(operation, result);
return;
}
} else if (error && error != [NSNull null]) {
if ([error isKindOfClass:[NSDictionary class]]) {
if (error[@"code"]) {
code = [error[@"code"] integerValue];
}
if (error[@"message"]) {
message = error[@"message"];
} else if (code) {
message = AFJSONRPCLocalizedErrorMessageForCode(code);
}
data = error[@"data"];
} else {
message = NSLocalizedStringFromTable(@"Unknown Error", @"AFJSONRPCClient", nil);
}
} else {
message = NSLocalizedStringFromTable(@"Unknown JSON-RPC Response", @"AFJSONRPCClient", nil);
}
} else {
message = NSLocalizedStringFromTable(@"Unknown JSON-RPC Response", @"AFJSONRPCClient", nil);
}
if (failure) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
if (message) {
userInfo[NSLocalizedDescriptionKey] = message;
}
if (data) {
userInfo[@"data"] = data;
}
NSError *error = [NSError errorWithDomain:AFJSONRPCErrorDomain code:code userInfo:userInfo];
failure(operation, error);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(operation, error);
}
}];
}
- (id)proxyWithProtocol:(Protocol *)protocol {
return [[AFJSONRPCProxy alloc] initWithClient:self protocol:protocol];
}
@end
#pragma mark -
typedef void (^AFJSONRPCProxySuccessBlock)(id responseObject);
typedef void (^AFJSONRPCProxyFailureBlock)(NSError *error);
@interface AFJSONRPCProxy ()
@property (readwrite, nonatomic, strong) AFJSONRPCClient *client;
@property (readwrite, nonatomic, strong) Protocol *protocol;
@end
@implementation AFJSONRPCProxy
- (id)initWithClient:(AFJSONRPCClient*)client
protocol:(Protocol *)protocol
{
self.client = client;
self.protocol = protocol;
return self;
}
- (BOOL)respondsToSelector:(SEL)selector {
struct objc_method_description description = protocol_getMethodDescription(self.protocol, selector, YES, YES);
return description.name != NULL;
}
- (NSMethodSignature *)methodSignatureForSelector:(__unused SEL)selector {
// 0: v->RET || 1: @->self || 2: :->SEL || 3: @->arg#0 (NSArray) || 4,5: ^v->arg#1,2 (block)
NSMethodSignature *signature = [NSMethodSignature signatureWithObjCTypes:"v@:@^v^v"];
return signature;
}
- (void)forwardInvocation:(NSInvocation *)invocation {
NSParameterAssert(invocation.methodSignature.numberOfArguments == 5);
NSString *RPCMethod = [NSStringFromSelector([invocation selector]) componentsSeparatedByString:@":"][0];
__unsafe_unretained id arguments;
__unsafe_unretained AFJSONRPCProxySuccessBlock unsafeSuccess;
__unsafe_unretained AFJSONRPCProxyFailureBlock unsafeFailure;
[invocation getArgument:&arguments atIndex:2];
[invocation getArgument:&unsafeSuccess atIndex:3];
[invocation getArgument:&unsafeFailure atIndex:4];
[invocation invokeWithTarget:nil];
__strong AFJSONRPCProxySuccessBlock strongSuccess = [unsafeSuccess copy];
__strong AFJSONRPCProxyFailureBlock strongFailure = [unsafeFailure copy];
[self.client invokeMethod:RPCMethod withParameters:arguments success:^(__unused AFHTTPRequestOperation *operation, id responseObject) {
if (strongSuccess) {
strongSuccess(responseObject);
}
} failure:^(__unused AFHTTPRequestOperation *operation, NSError *error) {
if (strongFailure) {
strongFailure(error);
}
}];
}
@end
Copyright (c) 2013 JustCommunication
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.
# AFJSONRPCClient
**A [JSON-RPC](http://json-rpc.org/) Client built on [AFNetworking](https://github.com/AFNetworking/AFNetworking)**
> [JSON-RPC](http://json-rpc.org/) is a [remote procedure call](http://en.wikipedia.org/wiki/Remote_procedure_call) protocol encoded in [JSON](http://en.wikipedia.org/wiki/JSON). It is a simple protocol (and very similar to [XML-RPC](http://en.wikipedia.org/wiki/XML-RPC)), defining only a handful of data types and commands. JSON-RPC allows for notifications (info sent to the server that does not require a response) and for multiple calls to be sent to the server which may be answered out of order.
## Example Usage
``` objective-c
AFJSONRPCClient *client = [AFJSONRPCClient clientWithEndpointURL:[NSURL URLWithString:@"http://path.to/json-rpc/service/"]];
// Invocation
[client invokeMethod:@"method.name"
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
// ...
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// ...
}];
// Invocation with Parameters
[client invokeMethod:@"method.name"
parameters:@{@"foo" : @"bar", @"baz" : @(13)}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// ...
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// ...
}];
// Invocation with Parameters and Request ID
[client invokeMethod:@"method.name"
parameters:@[@(YES), @(42)]
requestId:@(2)
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// ...
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// ...
}];
```
## Using Protocol & NSProxy
Combine your JSON-RPC client with an Objective-C protocol for fun and profit!
``` objective-c
@protocol ArithemeticProtocol
- (void)sum:(NSArray *)numbers
success:(void (^)(NSNumber *sum))success;
failure:(void (^)(NSError *error))failure;
@end
AFJSONRPCClient *client = [AFJSONRPCClient clientWithEndpointURL:[NSURL URLWithString:@"http://path.to/json-rpc/service/"]];
[[client proxyForProtocol:@protocol(ArithemeticProtocol)] sum:@[@(1), @(2)]
success:^(NSNumber *sum) {
// ...
} failure:^(NSError *error) {
// ...
}];
```
## Subclassing
You can also subclass `AFJSONRPCClient` for shared class and service-related methods:
``` objective-c
MyJSONRPCClient *client = [MyJSONRPCClient sharedClient];
[client sum:@[@(1), @(2)]
success:^(NSNumber *sum) {
// ...
} failure:^(NSError *error) {
// ...
}];
```
## Installation
[CocoaPods](http://cocoapods.org) is the recommended way to add AFJSONRPCClient to your project.
Here's an example podfile that installs AFJSONRPCClient and its dependency, AFNetworking.
### Podfile
```ruby
platform :ios, '5.0'
pod 'AFJSONRPCClient', '0.1.0'
```
Note the specification of iOS 5.0 as the platform; leaving out the 5.0 will cause CocoaPods to fail with the following message:
> [!] AFJSONRPCClient is not compatible with iOS 4.3.
## License
AFJSONRPCClient and AFNetworking are available under the MIT license. See the LICENSE file for more info.
// AFCompatibilityMacros.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// 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.
#ifndef AFCompatibilityMacros_h
#define AFCompatibilityMacros_h
#ifdef API_UNAVAILABLE
#define AF_API_UNAVAILABLE(x) API_UNAVAILABLE(x)
#else
#define AF_API_UNAVAILABLE(x)
#endif // API_UNAVAILABLE
#if __has_warning("-Wunguarded-availability-new")
#define AF_CAN_USE_AT_AVAILABLE 1
#else
#define AF_CAN_USE_AT_AVAILABLE 0
#endif
#endif /* AFCompatibilityMacros_h */
// AFHTTPRequestOperation.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 <Foundation/Foundation.h>
#import "AFURLConnectionOperation.h"
NS_ASSUME_NONNULL_BEGIN
/**
`AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
*/
@interface AFHTTPRequestOperation : AFURLConnectionOperation
///------------------------------------------------
/// @name Getting HTTP URL Connection Information
///------------------------------------------------
/**
The last HTTP response received by the operation's connection.
*/
@property (readonly, nonatomic, strong, nullable) NSHTTPURLResponse *response;
/**
Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an AFHTTPResponse serializer, which uses the raw data as its response object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed.
@warning `responseSerializer` must not be `nil`. Setting a response serializer will clear out any cached value
*/
@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
/**
An object constructed by the `responseSerializer` from the response and response data. Returns `nil` unless the operation `isFinished`, has a `response`, and has `responseData` with non-zero content length. If an error occurs during serialization, `nil` will be returned, and the `error` property will be populated with the serialization error.
*/
@property (readonly, nonatomic, strong, nullable) id responseObject;
///-----------------------------------------------------------
/// @name Setting Completion Block Success / Failure Callbacks
///-----------------------------------------------------------
/**
Sets the `completionBlock` property with a block that executes either the specified success or failure block, depending on the state of the request on completion. If `error` returns a value, which can be caused by an unacceptable status code or content type, then `failure` is executed. Otherwise, `success` is executed.
This method should be overridden in subclasses in order to specify the response object passed into the success block.
@param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request.
@param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request.
*/
- (void)setCompletionBlockWithSuccess:(nullable void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
@end
NS_ASSUME_NONNULL_END
// AFHTTPRequestOperation.m
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 "AFHTTPRequestOperation.h"
static dispatch_queue_t http_request_operation_processing_queue() {
static dispatch_queue_t af_http_request_operation_processing_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_http_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.http-request.processing", DISPATCH_QUEUE_CONCURRENT);
});
return af_http_request_operation_processing_queue;
}
static dispatch_group_t http_request_operation_completion_group() {
static dispatch_group_t af_http_request_operation_completion_group;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_http_request_operation_completion_group = dispatch_group_create();
});
return af_http_request_operation_completion_group;
}
#pragma mark -
@interface AFURLConnectionOperation ()
@property (readwrite, nonatomic, strong) NSURLRequest *request;
@property (readwrite, nonatomic, strong) NSURLResponse *response;
@end
@interface AFHTTPRequestOperation ()
@property (readwrite, nonatomic, strong) NSHTTPURLResponse *response;
@property (readwrite, nonatomic, strong, nullable) id responseObject;
@property (readwrite, nonatomic, strong) NSError *responseSerializationError;
@property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
@end
@implementation AFHTTPRequestOperation
@dynamic response;
@dynamic lock;
- (instancetype)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.responseSerializer = [AFHTTPResponseSerializer serializer];
return self;
}
- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
NSParameterAssert(responseSerializer);
[self.lock lock];
_responseSerializer = responseSerializer;
self.responseObject = nil;
self.responseSerializationError = nil;
[self.lock unlock];
}
- (id)responseObject {
[self.lock lock];
if (!_responseObject && [self isFinished] && !self.error) {
NSError *error = nil;
self.responseObject = [self.responseSerializer responseObjectForResponse:self.response data:self.responseData error:&error];
if (error) {
self.responseSerializationError = error;
}
}
[self.lock unlock];
return _responseObject;
}
- (NSError *)error {
if (_responseSerializationError) {
return _responseSerializationError;
} else {
return [super error];
}
}
#pragma mark - AFHTTPRequestOperation
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
// completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
#pragma clang diagnostic ignored "-Wgnu"
self.completionBlock = ^{
if (self.completionGroup) {
dispatch_group_enter(self.completionGroup);
}
dispatch_async(http_request_operation_processing_queue(), ^{
if (self.error) {
if (failure) {
dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
id responseObject = self.responseObject;
if (self.error) {
if (failure) {
dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
if (success) {
dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
success(self, responseObject);
});
}
}
}
if (self.completionGroup) {
dispatch_group_leave(self.completionGroup);
}
});
};
#pragma clang diagnostic pop
}
#pragma mark - AFURLRequestOperation
- (void)pause {
[super pause];
u_int64_t offset = 0;
if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
offset = [(NSNumber *)[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue];
} else {
offset = [(NSData *)[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length];
}
NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy];
if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) {
[mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"];
}
[mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"];
self.request = mutableURLRequest;
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
AFHTTPRequestOperation *operation = [super copyWithZone:zone];
operation.responseSerializer = [self.responseSerializer copyWithZone:zone];
operation.completionQueue = self.completionQueue;
operation.completionGroup = self.completionGroup;
return operation;
}
@end
// AFHTTPRequestOperationManager.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <Availability.h>
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#import <MobileCoreServices/MobileCoreServices.h>
#else
#import <CoreServices/CoreServices.h>
#endif
#import "AFHTTPRequestOperation.h"
#import "AFURLResponseSerialization.h"
#import "AFURLRequestSerialization.h"
#import "AFSecurityPolicy.h"
#import "AFNetworkReachabilityManager.h"
#ifndef NS_DESIGNATED_INITIALIZER
#if __has_attribute(objc_designated_initializer)
#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
#else
#define NS_DESIGNATED_INITIALIZER
#endif
#endif
NS_ASSUME_NONNULL_BEGIN
/**
`AFHTTPRequestOperationManager` encapsulates the common patterns of communicating with a web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as request operation management.
## Subclassing Notes
Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.
For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect.
## Methods to Override
To change the behavior of all request operation construction for an `AFHTTPRequestOperationManager` subclass, override `HTTPRequestOperationWithRequest:success:failure`.
## Serialization
Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to `<AFURLRequestSerialization>`.
Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>`
## URL Construction Using Relative Paths
For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`.
Below are a few examples of how `baseURL` and relative paths interact:
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
[NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
[NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz
[NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo
[NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo
[NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/
[NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
## Network Reachability Monitoring
Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details.
## NSSecureCoding & NSCopying Caveats
`AFHTTPRequestOperationManager` conforms to the `NSSecureCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however:
- Archives and copies of HTTP clients will be initialized with an empty operation queue.
- NSSecureCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set.
*/
@interface AFHTTPRequestOperationManager : NSObject <NSSecureCoding, NSCopying>
/**
The URL used to monitor reachability, and construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods.
*/
@property (readonly, nonatomic, strong, nullable) NSURL *baseURL;
/**
Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies.
@warning `requestSerializer` must not be `nil`.
*/
@property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
/**
Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to a JSON serializer, which serializes data from responses with a `application/json` MIME type, and falls back to the raw data object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed.
@warning `responseSerializer` must not be `nil`.
*/
@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
/**
The operation queue on which request operations are scheduled and run.
*/
@property (nonatomic, strong) NSOperationQueue *operationQueue;
///-------------------------------
/// @name Managing URL Credentials
///-------------------------------
/**
Whether request operations should consult the credential storage for authenticating the connection. `YES` by default.
@see AFURLConnectionOperation -shouldUseCredentialStorage
*/
@property (nonatomic, assign) BOOL shouldUseCredentialStorage;
/**
The credential used by request operations for authentication challenges.
@see AFURLConnectionOperation -credential
*/
@property (nonatomic, strong, nullable) NSURLCredential *credential;
///-------------------------------
/// @name Managing Security Policy
///-------------------------------
/**
The security policy used by created request operations to evaluate server trust for secure connections. `AFHTTPRequestOperationManager` uses the `defaultPolicy` unless otherwise specified.
*/
@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
///------------------------------------
/// @name Managing Network Reachability
///------------------------------------
/**
The network reachability manager. `AFHTTPRequestOperationManager` uses the `sharedManager` by default.
*/
@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
///-------------------------------
/// @name Managing Callback Queues
///-------------------------------
/**
The dispatch queue for the `completionBlock` of request operations. If `NULL` (default), the main queue is used.
*/
#if OS_OBJECT_USE_OBJC
@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue;
#else
@property (nonatomic, assign, nullable) dispatch_queue_t completionQueue;
#endif
/**
The dispatch group for the `completionBlock` of request operations. If `NULL` (default), a private dispatch group is used.
*/
#if OS_OBJECT_USE_OBJC
@property (nonatomic, strong, nullable) dispatch_group_t completionGroup;
#else
@property (nonatomic, assign, nullable) dispatch_group_t completionGroup;
#endif
///---------------------------------------------
/// @name Creating and Initializing HTTP Clients
///---------------------------------------------
/**
Creates and returns an `AFHTTPRequestOperationManager` object.
*/
+ (instancetype)manager;
/**
Initializes an `AFHTTPRequestOperationManager` object with the specified base URL.
This is the designated initializer.
@param url The base URL for the HTTP client.
@return The newly-initialized HTTP client
*/
- (instancetype)initWithBaseURL:(nullable NSURL *)url NS_DESIGNATED_INITIALIZER;
///---------------------------------------
/// @name Managing HTTP Request Operations
///---------------------------------------
/**
Creates an `AFHTTPRequestOperation`, and sets the response serializers to that of the HTTP client.
@param request The request object to be loaded asynchronously during execution of the operation.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
*/
- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
success:(nullable void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
///---------------------------
/// @name Making HTTP Requests
///---------------------------
/**
Creates and runs an `AFHTTPRequestOperation` with a `GET` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (nullable AFHTTPRequestOperation *)GET:(NSString *)URLString
parameters:(nullable id)parameters
success:(nullable void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(nullable void (^)(AFHTTPRequestOperation * __nullable operation, NSError *error))failure;
/**
Creates and runs an `AFHTTPRequestOperation` with a `HEAD` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes a single arguments: the request operation.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (nullable AFHTTPRequestOperation *)HEAD:(NSString *)URLString
parameters:(nullable id)parameters
success:(nullable void (^)(AFHTTPRequestOperation *operation))success
failure:(nullable void (^)(AFHTTPRequestOperation * __nullable operation, NSError *error))failure;
/**
Creates and runs an `AFHTTPRequestOperation` with a `POST` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (nullable AFHTTPRequestOperation *)POST:(NSString *)URLString
parameters:(nullable id)parameters
success:(nullable void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(nullable void (^)(AFHTTPRequestOperation * __nullable operation, NSError *error))failure;
/**
Creates and runs an `AFHTTPRequestOperation` with a multipart `POST` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (nullable AFHTTPRequestOperation *)POST:(NSString *)URLString
parameters:(nullable id)parameters
constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
success:(nullable void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(nullable void (^)(AFHTTPRequestOperation * __nullable operation, NSError *error))failure;
/**
Creates and runs an `AFHTTPRequestOperation` with a `PUT` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (nullable AFHTTPRequestOperation *)PUT:(NSString *)URLString
parameters:(nullable id)parameters
success:(nullable void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(nullable void (^)(AFHTTPRequestOperation * __nullable operation, NSError *error))failure;
/**
Creates and runs an `AFHTTPRequestOperation` with a `PATCH` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (nullable AFHTTPRequestOperation *)PATCH:(NSString *)URLString
parameters:(nullable id)parameters
success:(nullable void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(nullable void (^)(AFHTTPRequestOperation * __nullable operation, NSError *error))failure;
/**
Creates and runs an `AFHTTPRequestOperation` with a `DELETE` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (nullable AFHTTPRequestOperation *)DELETE:(NSString *)URLString
parameters:(nullable id)parameters
success:(nullable void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(nullable void (^)(AFHTTPRequestOperation * __nullable operation, NSError *error))failure;
@end
NS_ASSUME_NONNULL_END
// AFHTTPRequestOperationManager.m
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 <Foundation/Foundation.h>
#import "AFHTTPRequestOperationManager.h"
#import "AFHTTPRequestOperation.h"
#import <Availability.h>
#import <Security/Security.h>
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h>
#endif
@interface AFHTTPRequestOperationManager ()
@property (readwrite, nonatomic, strong) NSURL *baseURL;
@end
@implementation AFHTTPRequestOperationManager
+ (instancetype)manager {
return [[self alloc] initWithBaseURL:nil];
}
- (instancetype)init {
return [self initWithBaseURL:nil];
}
- (instancetype)initWithBaseURL:(NSURL *)url {
self = [super init];
if (!self) {
return nil;
}
// Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
url = [url URLByAppendingPathComponent:@""];
}
self.baseURL = url;
self.requestSerializer = [AFHTTPRequestSerializer serializer];
self.responseSerializer = [AFJSONResponseSerializer serializer];
self.securityPolicy = [AFSecurityPolicy defaultPolicy];
self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
self.operationQueue = [[NSOperationQueue alloc] init];
self.shouldUseCredentialStorage = YES;
return self;
}
#pragma mark -
#ifdef _SYSTEMCONFIGURATION_H
#endif
- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
NSParameterAssert(requestSerializer);
_requestSerializer = requestSerializer;
}
- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
NSParameterAssert(responseSerializer);
_responseSerializer = responseSerializer;
}
#pragma mark -
- (AFHTTPRequestOperation *)HTTPRequestOperationWithHTTPMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
if (serializationError) {
if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
#pragma clang diagnostic pop
}
return nil;
}
return [self HTTPRequestOperationWithRequest:request success:success failure:failure];
}
- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
success:(void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = self.responseSerializer;
operation.shouldUseCredentialStorage = self.shouldUseCredentialStorage;
operation.credential = self.credential;
operation.securityPolicy = self.securityPolicy;
[operation setCompletionBlockWithSuccess:success failure:failure];
operation.completionQueue = self.completionQueue;
operation.completionGroup = self.completionGroup;
return operation;
}
#pragma mark -
- (AFHTTPRequestOperation *)GET:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"GET" URLString:URLString parameters:parameters success:success failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
- (AFHTTPRequestOperation *)HEAD:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters success:^(AFHTTPRequestOperation *requestOperation, __unused id responseObject) {
if (success) {
success(requestOperation);
}
} failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
- (AFHTTPRequestOperation *)POST:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"POST" URLString:URLString parameters:parameters success:success failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
- (AFHTTPRequestOperation *)POST:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
success:(void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
if (serializationError) {
if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
#pragma clang diagnostic pop
}
return nil;
}
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
- (AFHTTPRequestOperation *)PUT:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters success:success failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
- (AFHTTPRequestOperation *)PATCH:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters success:success failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
- (AFHTTPRequestOperation *)DELETE:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id __nullable responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters success:success failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
#pragma mark - NSObject
- (NSString *)description {
return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.operationQueue];
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (id)initWithCoder:(NSCoder *)decoder {
NSURL *baseURL = [decoder decodeObjectForKey:NSStringFromSelector(@selector(baseURL))];
self = [self initWithBaseURL:baseURL];
if (!self) {
return nil;
}
self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))];
if (decodedPolicy) {
self.securityPolicy = decodedPolicy;
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))];
[coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))];
[coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
[coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
AFHTTPRequestOperationManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL];
HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone];
return HTTPClient;
}
@end
// AFHTTPSessionManager.h // AFHTTPSessionManager.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -23,9 +23,9 @@ ...@@ -23,9 +23,9 @@
#if !TARGET_OS_WATCH #if !TARGET_OS_WATCH
#import <SystemConfiguration/SystemConfiguration.h> #import <SystemConfiguration/SystemConfiguration.h>
#endif #endif
#import <TargetConditionals.h> #import <Availability.h>
#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV #if __IPHONE_OS_VERSION_MIN_REQUIRED
#import <MobileCoreServices/MobileCoreServices.h> #import <MobileCoreServices/MobileCoreServices.h>
#else #else
#import <CoreServices/CoreServices.h> #import <CoreServices/CoreServices.h>
...@@ -33,6 +33,14 @@ ...@@ -33,6 +33,14 @@
#import "AFURLSessionManager.h" #import "AFURLSessionManager.h"
#ifndef NS_DESIGNATED_INITIALIZER
#if __has_attribute(objc_designated_initializer)
#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
#else
#define NS_DESIGNATED_INITIALIZER
#endif
#endif
/** /**
`AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths. `AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths.
...@@ -44,7 +52,7 @@ ...@@ -44,7 +52,7 @@
## Methods to Override ## Methods to Override
To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:`. To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:completionHandler:`.
## Serialization ## Serialization
...@@ -71,6 +79,8 @@ ...@@ -71,6 +79,8 @@
@warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance.
*/ */
#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || TARGET_OS_WATCH
NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
@interface AFHTTPSessionManager : AFURLSessionManager <NSSecureCoding, NSCopying> @interface AFHTTPSessionManager : AFURLSessionManager <NSSecureCoding, NSCopying>
...@@ -94,15 +104,6 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -94,15 +104,6 @@ NS_ASSUME_NONNULL_BEGIN
*/ */
@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer; @property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
///-------------------------------
/// @name Managing Security Policy
///-------------------------------
/**
The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. A security policy configured with `AFSSLPinningModePublicKey` or `AFSSLPinningModeCertificate` can only be applied on a session manager initialized with a secure base URL (i.e. https). Applying a security policy with pinning enabled on an insecure session manager throws an `Invalid Security Policy` exception.
*/
@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
///--------------------- ///---------------------
/// @name Initialization /// @name Initialization
///--------------------- ///---------------------
...@@ -150,26 +151,8 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -150,26 +151,8 @@ NS_ASSUME_NONNULL_BEGIN
*/ */
- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString - (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(nullable id)parameters parameters:(nullable id)parameters
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success success:(nullable void (^)(NSURLSessionDataTask *task, id __nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure;
/**
Creates and runs an `NSURLSessionDataTask` with a `GET` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
*/
- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(nullable id)parameters
progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
/** /**
Creates and runs an `NSURLSessionDataTask` with a `HEAD` request. Creates and runs an `NSURLSessionDataTask` with a `HEAD` request.
...@@ -184,7 +167,7 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -184,7 +167,7 @@ NS_ASSUME_NONNULL_BEGIN
- (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString - (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString
parameters:(nullable id)parameters parameters:(nullable id)parameters
success:(nullable void (^)(NSURLSessionDataTask *task))success success:(nullable void (^)(NSURLSessionDataTask *task))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure;
/** /**
Creates and runs an `NSURLSessionDataTask` with a `POST` request. Creates and runs an `NSURLSessionDataTask` with a `POST` request.
...@@ -198,25 +181,8 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -198,25 +181,8 @@ NS_ASSUME_NONNULL_BEGIN
*/ */
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString - (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(nullable id)parameters parameters:(nullable id)parameters
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success success:(nullable void (^)(NSURLSessionDataTask *task, id __nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure;
/**
Creates and runs an `NSURLSessionDataTask` with a `POST` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
*/
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(nullable id)parameters
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
/** /**
Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request.
...@@ -232,27 +198,8 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -232,27 +198,8 @@ NS_ASSUME_NONNULL_BEGIN
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString - (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(nullable id)parameters parameters:(nullable id)parameters
constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success success:(nullable void (^)(NSURLSessionDataTask *task, id __nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure;
/**
Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
@param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
*/
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(nullable id)parameters
constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
/** /**
Creates and runs an `NSURLSessionDataTask` with a `PUT` request. Creates and runs an `NSURLSessionDataTask` with a `PUT` request.
...@@ -266,8 +213,8 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -266,8 +213,8 @@ NS_ASSUME_NONNULL_BEGIN
*/ */
- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString - (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString
parameters:(nullable id)parameters parameters:(nullable id)parameters
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success success:(nullable void (^)(NSURLSessionDataTask *task, id __nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure;
/** /**
Creates and runs an `NSURLSessionDataTask` with a `PATCH` request. Creates and runs an `NSURLSessionDataTask` with a `PATCH` request.
...@@ -281,8 +228,8 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -281,8 +228,8 @@ NS_ASSUME_NONNULL_BEGIN
*/ */
- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString - (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString
parameters:(nullable id)parameters parameters:(nullable id)parameters
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success success:(nullable void (^)(NSURLSessionDataTask *task, id __nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure;
/** /**
Creates and runs an `NSURLSessionDataTask` with a `DELETE` request. Creates and runs an `NSURLSessionDataTask` with a `DELETE` request.
...@@ -296,9 +243,11 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -296,9 +243,11 @@ NS_ASSUME_NONNULL_BEGIN
*/ */
- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString - (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString
parameters:(nullable id)parameters parameters:(nullable id)parameters
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success success:(nullable void (^)(NSURLSessionDataTask *task, id __nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure;
@end @end
NS_ASSUME_NONNULL_END NS_ASSUME_NONNULL_END
#endif
// AFHTTPSessionManager.m // AFHTTPSessionManager.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -21,20 +21,23 @@ ...@@ -21,20 +21,23 @@
#import "AFHTTPSessionManager.h" #import "AFHTTPSessionManager.h"
#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || TARGET_WATCH_OS
#import "AFURLRequestSerialization.h" #import "AFURLRequestSerialization.h"
#import "AFURLResponseSerialization.h" #import "AFURLResponseSerialization.h"
#import <Availability.h> #import <Availability.h>
#import <TargetConditionals.h>
#import <Security/Security.h> #import <Security/Security.h>
#ifdef _SYSTEMCONFIGURATION_H
#import <netinet/in.h> #import <netinet/in.h>
#import <netinet6/in6.h> #import <netinet6/in6.h>
#import <arpa/inet.h> #import <arpa/inet.h>
#import <ifaddrs.h> #import <ifaddrs.h>
#import <netdb.h> #import <netdb.h>
#endif
#if TARGET_OS_IOS || TARGET_OS_TV #if TARGET_OS_IOS
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
#elif TARGET_OS_WATCH #elif TARGET_OS_WATCH
#import <WatchKit/WatchKit.h> #import <WatchKit/WatchKit.h>
...@@ -86,6 +89,9 @@ ...@@ -86,6 +89,9 @@
#pragma mark - #pragma mark -
#ifdef _SYSTEMCONFIGURATION_H
#endif
- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer { - (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
NSParameterAssert(requestSerializer); NSParameterAssert(requestSerializer);
...@@ -98,48 +104,14 @@ ...@@ -98,48 +104,14 @@
[super setResponseSerializer:responseSerializer]; [super setResponseSerializer:responseSerializer];
} }
@dynamic securityPolicy;
- (void)setSecurityPolicy:(AFSecurityPolicy *)securityPolicy {
if (securityPolicy.SSLPinningMode != AFSSLPinningModeNone && ![self.baseURL.scheme isEqualToString:@"https"]) {
NSString *pinningMode = @"Unknown Pinning Mode";
switch (securityPolicy.SSLPinningMode) {
case AFSSLPinningModeNone: pinningMode = @"AFSSLPinningModeNone"; break;
case AFSSLPinningModeCertificate: pinningMode = @"AFSSLPinningModeCertificate"; break;
case AFSSLPinningModePublicKey: pinningMode = @"AFSSLPinningModePublicKey"; break;
}
NSString *reason = [NSString stringWithFormat:@"A security policy configured with `%@` can only be applied on a manager with a secure base URL (i.e. https)", pinningMode];
@throw [NSException exceptionWithName:@"Invalid Security Policy" reason:reason userInfo:nil];
}
[super setSecurityPolicy:securityPolicy];
}
#pragma mark - #pragma mark -
- (NSURLSessionDataTask *)GET:(NSString *)URLString - (NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(id)parameters parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success success:(void (^)(NSURLSessionDataTask *task, id __nullable responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{ {
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" URLString:URLString parameters:parameters success:success failure:failure];
return [self GET:URLString parameters:parameters progress:nil success:success failure:failure];
}
- (NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(id)parameters
progress:(void (^)(NSProgress * _Nonnull))downloadProgress
success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET"
URLString:URLString
parameters:parameters
uploadProgress:nil
downloadProgress:downloadProgress
success:success
failure:failure];
[dataTask resume]; [dataTask resume];
...@@ -151,7 +123,7 @@ ...@@ -151,7 +123,7 @@
success:(void (^)(NSURLSessionDataTask *task))success success:(void (^)(NSURLSessionDataTask *task))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{ {
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) { NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters success:^(NSURLSessionDataTask *task, __unused id responseObject) {
if (success) { if (success) {
success(task); success(task);
} }
...@@ -164,19 +136,10 @@ ...@@ -164,19 +136,10 @@
- (NSURLSessionDataTask *)POST:(NSString *)URLString - (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success success:(void (^)(NSURLSessionDataTask *task, id __nullable responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{ {
return [self POST:URLString parameters:parameters progress:nil success:success failure:failure]; NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters success:success failure:failure];
}
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters
progress:(void (^)(NSProgress * _Nonnull))uploadProgress
success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure];
[dataTask resume]; [dataTask resume];
...@@ -184,34 +147,27 @@ ...@@ -184,34 +147,27 @@
} }
- (NSURLSessionDataTask *)POST:(NSString *)URLString - (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(nullable id)parameters
constructingBodyWithBlock:(nullable void (^)(id<AFMultipartFormData> _Nonnull))block
success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
return [self POST:URLString parameters:parameters constructingBodyWithBlock:block progress:nil success:success failure:failure];
}
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress success:(void (^)(NSURLSessionDataTask *task, id __nullable responseObject))success
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{ {
NSError *serializationError = nil; NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError]; NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
if (serializationError) { if (serializationError) {
if (failure) { if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError); failure(nil, serializationError);
}); });
#pragma clang diagnostic pop
} }
return nil; return nil;
} }
__block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * __unused response, id __nullable responseObject, NSError *error) {
if (error) { if (error) {
if (failure) { if (failure) {
failure(task, error); failure(task, error);
...@@ -230,10 +186,10 @@ ...@@ -230,10 +186,10 @@
- (NSURLSessionDataTask *)PUT:(NSString *)URLString - (NSURLSessionDataTask *)PUT:(NSString *)URLString
parameters:(id)parameters parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success success:(void (^)(NSURLSessionDataTask *task, id __nullable responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{ {
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters success:success failure:failure];
[dataTask resume]; [dataTask resume];
...@@ -242,10 +198,10 @@ ...@@ -242,10 +198,10 @@
- (NSURLSessionDataTask *)PATCH:(NSString *)URLString - (NSURLSessionDataTask *)PATCH:(NSString *)URLString
parameters:(id)parameters parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success success:(void (^)(NSURLSessionDataTask *task, id __nullable responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{ {
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters success:success failure:failure];
[dataTask resume]; [dataTask resume];
...@@ -254,10 +210,10 @@ ...@@ -254,10 +210,10 @@
- (NSURLSessionDataTask *)DELETE:(NSString *)URLString - (NSURLSessionDataTask *)DELETE:(NSString *)URLString
parameters:(id)parameters parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success success:(void (^)(NSURLSessionDataTask *task, id __nullable responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{ {
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters success:success failure:failure];
[dataTask resume]; [dataTask resume];
...@@ -267,8 +223,6 @@ ...@@ -267,8 +223,6 @@
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method - (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
URLString:(NSString *)URLString URLString:(NSString *)URLString
parameters:(id)parameters parameters:(id)parameters
uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
success:(void (^)(NSURLSessionDataTask *, id))success success:(void (^)(NSURLSessionDataTask *, id))success
failure:(void (^)(NSURLSessionDataTask *, NSError *))failure failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
{ {
...@@ -276,19 +230,19 @@ ...@@ -276,19 +230,19 @@
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError]; NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
if (serializationError) { if (serializationError) {
if (failure) { if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError); failure(nil, serializationError);
}); });
#pragma clang diagnostic pop
} }
return nil; return nil;
} }
__block NSURLSessionDataTask *dataTask = nil; __block NSURLSessionDataTask *dataTask = nil;
dataTask = [self dataTaskWithRequest:request dataTask = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * __unused response, id __nullable responseObject, NSError *error) {
uploadProgress:uploadProgress
downloadProgress:downloadProgress
completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
if (error) { if (error) {
if (failure) { if (failure) {
failure(dataTask, error); failure(dataTask, error);
...@@ -315,7 +269,7 @@ ...@@ -315,7 +269,7 @@
return YES; return YES;
} }
- (instancetype)initWithCoder:(NSCoder *)decoder { - (id)initWithCoder:(NSCoder *)decoder {
NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))]; NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))];
NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
if (!configuration) { if (!configuration) {
...@@ -360,7 +314,7 @@ ...@@ -360,7 +314,7 @@
#pragma mark - NSCopying #pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone { - (id)copyWithZone:(NSZone *)zone {
AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration]; AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration];
HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
...@@ -370,3 +324,5 @@ ...@@ -370,3 +324,5 @@
} }
@end @end
#endif
// AFNetworkReachabilityManager.h // AFNetworkReachabilityManager.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -24,6 +24,14 @@ ...@@ -24,6 +24,14 @@
#if !TARGET_OS_WATCH #if !TARGET_OS_WATCH
#import <SystemConfiguration/SystemConfiguration.h> #import <SystemConfiguration/SystemConfiguration.h>
#ifndef NS_DESIGNATED_INITIALIZER
#if __has_attribute(objc_designated_initializer)
#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
#else
#define NS_DESIGNATED_INITIALIZER
#endif
#endif
typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
AFNetworkReachabilityStatusUnknown = -1, AFNetworkReachabilityStatusUnknown = -1,
AFNetworkReachabilityStatusNotReachable = 0, AFNetworkReachabilityStatusNotReachable = 0,
...@@ -38,7 +46,7 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -38,7 +46,7 @@ NS_ASSUME_NONNULL_BEGIN
Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability. Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability.
See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ ) See Apple's Reachability Sample Code (https://developer.apple.com/library/ios/samplecode/reachability/)
@warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined. @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
*/ */
...@@ -74,13 +82,6 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -74,13 +82,6 @@ NS_ASSUME_NONNULL_BEGIN
+ (instancetype)sharedManager; + (instancetype)sharedManager;
/** /**
Creates and returns a network reachability manager with the default socket address.
@return An initialized network reachability manager, actively monitoring the default socket address.
*/
+ (instancetype)manager;
/**
Creates and returns a network reachability manager for the specified domain. Creates and returns a network reachability manager for the specified domain.
@param domain The domain used to evaluate network reachability. @param domain The domain used to evaluate network reachability.
...@@ -92,7 +93,7 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -92,7 +93,7 @@ NS_ASSUME_NONNULL_BEGIN
/** /**
Creates and returns a network reachability manager for the socket address. Creates and returns a network reachability manager for the socket address.
@param address The socket address (`sockaddr_in6`) used to evaluate network reachability. @param address The socket address (`sockaddr_in`) used to evaluate network reachability.
@return An initialized network reachability manager, actively monitoring the specified socket address. @return An initialized network reachability manager, actively monitoring the specified socket address.
*/ */
......
// AFNetworkReachabilityManager.m // AFNetworkReachabilityManager.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -94,7 +94,6 @@ static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused targ ...@@ -94,7 +94,6 @@ static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused targ
AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusBlock)info); AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusBlock)info);
} }
static const void * AFNetworkReachabilityRetainCallback(const void *info) { static const void * AFNetworkReachabilityRetainCallback(const void *info) {
return Block_copy(info); return Block_copy(info);
} }
...@@ -117,7 +116,12 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) { ...@@ -117,7 +116,12 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
static AFNetworkReachabilityManager *_sharedManager = nil; static AFNetworkReachabilityManager *_sharedManager = nil;
static dispatch_once_t onceToken; static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ dispatch_once(&onceToken, ^{
_sharedManager = [self manager]; struct sockaddr_in address;
bzero(&address, sizeof(address));
address.sin_len = sizeof(address);
address.sin_family = AF_INET;
_sharedManager = [self managerForAddress:&address];
}); });
return _sharedManager; return _sharedManager;
...@@ -142,22 +146,6 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) { ...@@ -142,22 +146,6 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
return manager; return manager;
} }
+ (instancetype)manager
{
#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100)
struct sockaddr_in6 address;
bzero(&address, sizeof(address));
address.sin6_len = sizeof(address);
address.sin6_family = AF_INET6;
#else
struct sockaddr_in address;
bzero(&address, sizeof(address));
address.sin_len = sizeof(address);
address.sin_family = AF_INET;
#endif
return [self managerForAddress:&address];
}
- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability {
self = [super init]; self = [super init];
if (!self) { if (!self) {
...@@ -170,7 +158,7 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) { ...@@ -170,7 +158,7 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
return self; return self;
} }
- (instancetype)init - (instancetype)init NS_UNAVAILABLE
{ {
@throw [NSException exceptionWithName:NSGenericException @throw [NSException exceptionWithName:NSGenericException
reason:@"`-init` unavailable. Use `-initWithReachability:` instead" reason:@"`-init` unavailable. Use `-initWithReachability:` instead"
......
...@@ -22,7 +22,6 @@ ...@@ -22,7 +22,6 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <Availability.h> #import <Availability.h>
#import <TargetConditionals.h>
#ifndef _AFNETWORKING_ #ifndef _AFNETWORKING_
#define _AFNETWORKING_ #define _AFNETWORKING_
...@@ -30,12 +29,18 @@ ...@@ -30,12 +29,18 @@
#import "AFURLRequestSerialization.h" #import "AFURLRequestSerialization.h"
#import "AFURLResponseSerialization.h" #import "AFURLResponseSerialization.h"
#import "AFSecurityPolicy.h" #import "AFSecurityPolicy.h"
#if !TARGET_OS_WATCH #if !TARGET_OS_WATCH
#import "AFNetworkReachabilityManager.h" #import "AFNetworkReachabilityManager.h"
#import "AFURLConnectionOperation.h"
#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"
#endif #endif
#if ( ( defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || \
( defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 ) || \
TARGET_OS_WATCH )
#import "AFURLSessionManager.h" #import "AFURLSessionManager.h"
#import "AFHTTPSessionManager.h" #import "AFHTTPSessionManager.h"
#endif
#endif /* _AFNETWORKING_ */ #endif /* _AFNETWORKING_ */
// AFSecurityPolicy.h // AFSecurityPolicy.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -44,13 +44,9 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -44,13 +44,9 @@ NS_ASSUME_NONNULL_BEGIN
@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode; @property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
/** /**
The certificates used to evaluate server trust according to the SSL pinning mode. The certificates used to evaluate server trust according to the SSL pinning mode. By default, this property is set to any (`.cer`) certificates included in the app bundle. Note that if you create an array with duplicate certificates, the duplicate certificates will be removed. Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches.
By default, this property is set to any (`.cer`) certificates included in the target compiling AFNetworking. Note that if you are using AFNetworking as embedded framework, no certificates will be pinned by default. Use `certificatesInBundle` to load certificates from your target, and then create a new policy by calling `policyWithPinningMode:withPinnedCertificates`.
Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches.
*/ */
@property (nonatomic, strong, nullable) NSSet <NSData *> *pinnedCertificates; @property (nonatomic, strong, nullable) NSArray *pinnedCertificates;
/** /**
Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`.
...@@ -63,17 +59,6 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -63,17 +59,6 @@ NS_ASSUME_NONNULL_BEGIN
@property (nonatomic, assign) BOOL validatesDomainName; @property (nonatomic, assign) BOOL validatesDomainName;
///----------------------------------------- ///-----------------------------------------
/// @name Getting Certificates from the Bundle
///-----------------------------------------
/**
Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`.
@return The certificates included in the given bundle.
*/
+ (NSSet <NSData *> *)certificatesInBundle:(NSBundle *)bundle;
///-----------------------------------------
/// @name Getting Specific Security Policies /// @name Getting Specific Security Policies
///----------------------------------------- ///-----------------------------------------
...@@ -97,19 +82,22 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -97,19 +82,22 @@ NS_ASSUME_NONNULL_BEGIN
*/ */
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode;
///------------------------------
/// @name Evaluating Server Trust
///------------------------------
/** /**
Creates and returns a security policy with the specified pinning mode. Whether or not the specified server trust should be accepted, based on the security policy.
@param pinningMode The SSL pinning mode. This method should be used when responding to an authentication challenge from a server.
@param pinnedCertificates The certificates to pin against.
@return A new security policy. @param serverTrust The X.509 certificate trust of the server.
*/
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet <NSData *> *)pinnedCertificates;
///------------------------------ @return Whether or not to trust the server.
/// @name Evaluating Server Trust
///------------------------------ @warning This method has been deprecated in favor of `-evaluateServerTrust:forDomain:`.
*/
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust DEPRECATED_ATTRIBUTE;
/** /**
Whether or not the specified server trust should be accepted, based on the security policy. Whether or not the specified server trust should be accepted, based on the security policy.
......
// AFSecurityPolicy.m // AFSecurityPolicy.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
#import <AssertMacros.h> #import <AssertMacros.h>
#if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV #if !TARGET_OS_IOS && !TARGET_OS_WATCH
static NSData * AFSecKeyGetData(SecKeyRef key) { static NSData * AFSecKeyGetData(SecKeyRef key) {
CFDataRef data = NULL; CFDataRef data = NULL;
...@@ -41,7 +41,7 @@ _out: ...@@ -41,7 +41,7 @@ _out:
#endif #endif
static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV #if TARGET_OS_IOS || TARGET_OS_WATCH
return [(__bridge id)key1 isEqual:(__bridge id)key2]; return [(__bridge id)key1 isEqual:(__bridge id)key2];
#else #else
return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)]; return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)];
...@@ -51,6 +51,8 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { ...@@ -51,6 +51,8 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
static id AFPublicKeyForCertificate(NSData *certificate) { static id AFPublicKeyForCertificate(NSData *certificate) {
id allowedPublicKey = nil; id allowedPublicKey = nil;
SecCertificateRef allowedCertificate; SecCertificateRef allowedCertificate;
SecCertificateRef allowedCertificates[1];
CFArrayRef tempCertificates = nil;
SecPolicyRef policy = nil; SecPolicyRef policy = nil;
SecTrustRef allowedTrust = nil; SecTrustRef allowedTrust = nil;
SecTrustResultType result; SecTrustResultType result;
...@@ -58,8 +60,11 @@ static id AFPublicKeyForCertificate(NSData *certificate) { ...@@ -58,8 +60,11 @@ static id AFPublicKeyForCertificate(NSData *certificate) {
allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
__Require_Quiet(allowedCertificate != NULL, _out); __Require_Quiet(allowedCertificate != NULL, _out);
allowedCertificates[0] = allowedCertificate;
tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);
policy = SecPolicyCreateBasicX509(); policy = SecPolicyCreateBasicX509();
__Require_noErr_Quiet(SecTrustCreateWithCertificates(allowedCertificate, policy, &allowedTrust), _out); __Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out);
__Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out); __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out);
allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);
...@@ -73,6 +78,10 @@ _out: ...@@ -73,6 +78,10 @@ _out:
CFRelease(policy); CFRelease(policy);
} }
if (tempCertificates) {
CFRelease(tempCertificates);
}
if (allowedCertificate) { if (allowedCertificate) {
CFRelease(allowedCertificate); CFRelease(allowedCertificate);
} }
...@@ -141,29 +150,25 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { ...@@ -141,29 +150,25 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
@interface AFSecurityPolicy() @interface AFSecurityPolicy()
@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode; @property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
@property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys; @property (readwrite, nonatomic, strong) NSArray *pinnedPublicKeys;
@end @end
@implementation AFSecurityPolicy @implementation AFSecurityPolicy
+ (NSSet *)certificatesInBundle:(NSBundle *)bundle { + (NSArray *)defaultPinnedCertificates {
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; static NSArray *_defaultPinnedCertificates = nil;
NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]];
for (NSString *path in paths) {
NSData *certificateData = [NSData dataWithContentsOfFile:path];
[certificates addObject:certificateData];
}
return [NSSet setWithSet:certificates];
}
+ (NSSet *)defaultPinnedCertificates {
static NSSet *_defaultPinnedCertificates = nil;
static dispatch_once_t onceToken; static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ dispatch_once(&onceToken, ^{
NSBundle *bundle = [NSBundle bundleForClass:[self class]]; NSBundle *bundle = [NSBundle bundleForClass:[self class]];
_defaultPinnedCertificates = [self certificatesInBundle:bundle]; 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; return _defaultPinnedCertificates;
...@@ -177,19 +182,15 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { ...@@ -177,19 +182,15 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
} }
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode {
return [self policyWithPinningMode:pinningMode withPinnedCertificates:[self defaultPinnedCertificates]];
}
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates {
AFSecurityPolicy *securityPolicy = [[self alloc] init]; AFSecurityPolicy *securityPolicy = [[self alloc] init];
securityPolicy.SSLPinningMode = pinningMode; securityPolicy.SSLPinningMode = pinningMode;
[securityPolicy setPinnedCertificates:pinnedCertificates]; [securityPolicy setPinnedCertificates:[self defaultPinnedCertificates]];
return securityPolicy; return securityPolicy;
} }
- (instancetype)init { - (id)init {
self = [super init]; self = [super init];
if (!self) { if (!self) {
return nil; return nil;
...@@ -200,11 +201,11 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { ...@@ -200,11 +201,11 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
return self; return self;
} }
- (void)setPinnedCertificates:(NSSet *)pinnedCertificates { - (void)setPinnedCertificates:(NSArray *)pinnedCertificates {
_pinnedCertificates = pinnedCertificates; _pinnedCertificates = [[NSOrderedSet orderedSetWithArray:pinnedCertificates] array];
if (self.pinnedCertificates) { if (self.pinnedCertificates) {
NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]]; NSMutableArray *mutablePinnedPublicKeys = [NSMutableArray arrayWithCapacity:[self.pinnedCertificates count]];
for (NSData *certificate in self.pinnedCertificates) { for (NSData *certificate in self.pinnedCertificates) {
id publicKey = AFPublicKeyForCertificate(certificate); id publicKey = AFPublicKeyForCertificate(certificate);
if (!publicKey) { if (!publicKey) {
...@@ -212,7 +213,7 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { ...@@ -212,7 +213,7 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
} }
[mutablePinnedPublicKeys addObject:publicKey]; [mutablePinnedPublicKeys addObject:publicKey];
} }
self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys]; self.pinnedPublicKeys = [NSArray arrayWithArray:mutablePinnedPublicKeys];
} else { } else {
self.pinnedPublicKeys = nil; self.pinnedPublicKeys = nil;
} }
...@@ -220,6 +221,10 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { ...@@ -220,6 +221,10 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
#pragma mark - #pragma mark -
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust {
return [self evaluateServerTrust:serverTrust forDomain:nil];
}
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
forDomain:(NSString *)domain forDomain:(NSString *)domain
{ {
...@@ -251,6 +256,7 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { ...@@ -251,6 +256,7 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
return NO; return NO;
} }
NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust);
switch (self.SSLPinningMode) { switch (self.SSLPinningMode) {
case AFSSLPinningModeNone: case AFSSLPinningModeNone:
default: default:
...@@ -266,16 +272,13 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { ...@@ -266,16 +272,13 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
return NO; return NO;
} }
// obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA) NSUInteger trustedCertificateCount = 0;
NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); for (NSData *trustChainCertificate in serverCertificates) {
for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) {
if ([self.pinnedCertificates containsObject:trustChainCertificate]) { if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
return YES; trustedCertificateCount++;
} }
} }
return trustedCertificateCount > 0;
return NO;
} }
case AFSSLPinningModePublicKey: { case AFSSLPinningModePublicKey: {
NSUInteger trustedPublicKeyCount = 0; NSUInteger trustedPublicKeyCount = 0;
......
// AFURLConnectionOperation.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 <Foundation/Foundation.h>
#import <Availability.h>
#import "AFURLRequestSerialization.h"
#import "AFURLResponseSerialization.h"
#import "AFSecurityPolicy.h"
#ifndef NS_DESIGNATED_INITIALIZER
#if __has_attribute(objc_designated_initializer)
#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
#else
#define NS_DESIGNATED_INITIALIZER
#endif
#endif
/**
`AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods.
## Subclassing Notes
This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors.
If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes.
## NSURLConnection Delegate Methods
`AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods:
- `connection:didReceiveResponse:`
- `connection:didReceiveData:`
- `connectionDidFinishLoading:`
- `connection:didFailWithError:`
- `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:`
- `connection:willCacheResponse:`
- `connectionShouldUseCredentialStorage:`
- `connection:needNewBodyStream:`
- `connection:willSendRequestForAuthenticationChallenge:`
If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
## Callbacks and Completion Blocks
The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this.
Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/).
## SSL Pinning
Relying on the CA trust model to validate SSL certificates exposes your app to security vulnerabilities, such as man-in-the-middle attacks. For applications that connect to known servers, SSL certificate pinning provides an increased level of security, by checking server certificate validity against those specified in the app bundle.
SSL with certificate pinning is strongly recommended for any application that transmits sensitive information to an external webservice.
Connections will be validated on all matching certificates with a `.cer` extension in the bundle root.
## NSCoding & NSCopying Conformance
`AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind:
### NSCoding Caveats
- Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`.
- Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged.
### NSCopying Caveats
- `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations.
- A copy of an operation will not include the `outputStream` of the original.
- Operation copies do not include `completionBlock`, as it often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied.
*/
NS_ASSUME_NONNULL_BEGIN
@interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate, NSURLConnectionDataDelegate, NSSecureCoding, NSCopying>
///-------------------------------
/// @name Accessing Run Loop Modes
///-------------------------------
/**
The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`.
*/
@property (nonatomic, strong) NSSet *runLoopModes;
///-----------------------------------------
/// @name Getting URL Connection Information
///-----------------------------------------
/**
The request used by the operation's connection.
*/
@property (readonly, nonatomic, strong) NSURLRequest *request;
/**
The last response received by the operation's connection.
*/
@property (readonly, nonatomic, strong, nullable) NSURLResponse *response;
/**
The error, if any, that occurred in the lifecycle of the request.
*/
@property (readonly, nonatomic, strong, nullable) NSError *error;
///----------------------------
/// @name Getting Response Data
///----------------------------
/**
The data received during the request.
*/
@property (readonly, nonatomic, strong, nullable) NSData *responseData;
/**
The string representation of the response data.
*/
@property (readonly, nonatomic, copy, nullable) NSString *responseString;
/**
The string encoding of the response.
If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`.
*/
@property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding;
///-------------------------------
/// @name Managing URL Credentials
///-------------------------------
/**
Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default.
This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`.
*/
@property (nonatomic, assign) BOOL shouldUseCredentialStorage;
/**
The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`.
This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
*/
@property (nonatomic, strong, nullable) NSURLCredential *credential;
///-------------------------------
/// @name Managing Security Policy
///-------------------------------
/**
The security policy used to evaluate server trust for secure connections.
*/
@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
///------------------------
/// @name Accessing Streams
///------------------------
/**
The input stream used to read data to be sent during the request.
This property acts as a proxy to the `HTTPBodyStream` property of `request`.
*/
@property (nonatomic, strong) NSInputStream *inputStream;
/**
The output stream that is used to write data received until the request is finished.
By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request, with the intermediary `outputStream` property set to `nil`. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set.
*/
@property (nonatomic, strong, nullable) NSOutputStream *outputStream;
///---------------------------------
/// @name Managing Callback Queues
///---------------------------------
/**
The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
*/
#if OS_OBJECT_USE_OBJC
@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue;
#else
@property (nonatomic, assign, nullable) dispatch_queue_t completionQueue;
#endif
/**
The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
*/
#if OS_OBJECT_USE_OBJC
@property (nonatomic, strong, nullable) dispatch_group_t completionGroup;
#else
@property (nonatomic, assign, nullable) dispatch_group_t completionGroup;
#endif
///---------------------------------------------
/// @name Managing Request Operation Information
///---------------------------------------------
/**
The user info dictionary for the receiver.
*/
@property (nonatomic, strong) NSDictionary *userInfo;
// FIXME: It doesn't seem that this userInfo is used anywhere in the implementation.
///------------------------------------------------------
/// @name Initializing an AFURLConnectionOperation Object
///------------------------------------------------------
/**
Initializes and returns a newly allocated operation object with a url connection configured with the specified url request.
This is the designated initializer.
@param urlRequest The request object to be used by the operation connection.
*/
- (instancetype)initWithRequest:(NSURLRequest *)urlRequest NS_DESIGNATED_INITIALIZER;
///----------------------------------
/// @name Pausing / Resuming Requests
///----------------------------------
/**
Pauses the execution of the request operation.
A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect.
*/
- (void)pause;
/**
Whether the request operation is currently paused.
@return `YES` if the operation is currently paused, otherwise `NO`.
*/
- (BOOL)isPaused;
/**
Resumes the execution of the paused request operation.
Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request.
*/
- (void)resume;
///----------------------------------------------
/// @name Configuring Backgrounding Task Behavior
///----------------------------------------------
/**
Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task.
@param handler A handler to be called shortly before the application’s remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified.
*/
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(nullable void (^)(void))handler NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions.");
#endif
///---------------------------------
/// @name Setting Progress Callbacks
///---------------------------------
/**
Sets a callback to be called when an undetermined number of bytes have been uploaded to the server.
@param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes three arguments: the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread.
*/
- (void)setUploadProgressBlock:(nullable void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block;
/**
Sets a callback to be called when an undetermined number of bytes have been downloaded from the server.
@param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread.
*/
- (void)setDownloadProgressBlock:(nullable void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block;
///-------------------------------------------------
/// @name Setting NSURLConnection Delegate Callbacks
///-------------------------------------------------
/**
Sets a block to be executed when the connection will authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequestForAuthenticationChallenge:`.
@param block A block object to be executed when the connection will authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated. This block must invoke one of the challenge-responder methods (NSURLAuthenticationChallengeSender protocol).
If `allowsInvalidSSLCertificate` is set to YES, `connection:willSendRequestForAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates.
*/
- (void)setWillSendRequestForAuthenticationChallengeBlock:(nullable void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block;
/**
Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDataDelegate` method `connection:willSendRequest:redirectResponse:`.
@param block A block object to be executed when the request URL was changed. The block returns an `NSURLRequest` object, the URL request to redirect, and takes three arguments: the URL connection object, the the proposed redirected request, and the URL response that caused the redirect.
*/
- (void)setRedirectResponseBlock:(nullable NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block;
/**
Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`.
@param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request.
*/
- (void)setCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block;
///
/**
*/
+ (NSArray *)batchOfRequestOperations:(nullable NSArray *)operations
progressBlock:(nullable void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(nullable void (^)(NSArray *operations))completionBlock;
@end
///--------------------
/// @name Notifications
///--------------------
/**
Posted when an operation begins executing.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingOperationDidStartNotification;
/**
Posted when an operation finishes.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingOperationDidFinishNotification;
NS_ASSUME_NONNULL_END
// AFURLConnectionOperation.m
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 "AFURLConnectionOperation.h"
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h>
#endif
#if !__has_feature(objc_arc)
#error AFNetworking must be built with ARC.
// You can turn on ARC for only AFNetworking files by adding -fobjc-arc to the build phase for each of its files.
#endif
typedef NS_ENUM(NSInteger, AFOperationState) {
AFOperationPausedState = -1,
AFOperationReadyState = 1,
AFOperationExecutingState = 2,
AFOperationFinishedState = 3,
};
static dispatch_group_t url_request_operation_completion_group() {
static dispatch_group_t af_url_request_operation_completion_group;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_url_request_operation_completion_group = dispatch_group_create();
});
return af_url_request_operation_completion_group;
}
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;
}
static NSString * const kAFNetworkingLockName = @"com.alamofire.networking.operation.lock";
NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start";
NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish";
typedef void (^AFURLConnectionOperationProgressBlock)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected);
typedef void (^AFURLConnectionOperationAuthenticationChallengeBlock)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge);
typedef NSCachedURLResponse * (^AFURLConnectionOperationCacheResponseBlock)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse);
typedef NSURLRequest * (^AFURLConnectionOperationRedirectResponseBlock)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse);
typedef void (^AFURLConnectionOperationBackgroundTaskCleanupBlock)();
static inline NSString * AFKeyPathFromOperationState(AFOperationState state) {
switch (state) {
case AFOperationReadyState:
return @"isReady";
case AFOperationExecutingState:
return @"isExecuting";
case AFOperationFinishedState:
return @"isFinished";
case AFOperationPausedState:
return @"isPaused";
default: {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
return @"state";
#pragma clang diagnostic pop
}
}
}
static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperationState toState, BOOL isCancelled) {
switch (fromState) {
case AFOperationReadyState:
switch (toState) {
case AFOperationPausedState:
case AFOperationExecutingState:
return YES;
case AFOperationFinishedState:
return isCancelled;
default:
return NO;
}
case AFOperationExecutingState:
switch (toState) {
case AFOperationPausedState:
case AFOperationFinishedState:
return YES;
default:
return NO;
}
case AFOperationFinishedState:
return NO;
case AFOperationPausedState:
return toState == AFOperationReadyState;
default: {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
switch (toState) {
case AFOperationPausedState:
case AFOperationReadyState:
case AFOperationExecutingState:
case AFOperationFinishedState:
return YES;
default:
return NO;
}
}
#pragma clang diagnostic pop
}
}
@interface AFURLConnectionOperation ()
@property (readwrite, nonatomic, assign) AFOperationState state;
@property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
@property (readwrite, nonatomic, strong) NSURLConnection *connection;
@property (readwrite, nonatomic, strong) NSURLRequest *request;
@property (readwrite, nonatomic, strong) NSURLResponse *response;
@property (readwrite, nonatomic, strong) NSError *error;
@property (readwrite, nonatomic, strong) NSData *responseData;
@property (readwrite, nonatomic, copy) NSString *responseString;
@property (readwrite, nonatomic, assign) NSStringEncoding responseStringEncoding;
@property (readwrite, nonatomic, assign) long long totalBytesRead;
@property (readwrite, nonatomic, copy) AFURLConnectionOperationBackgroundTaskCleanupBlock backgroundTaskCleanup;
@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress;
@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress;
@property (readwrite, nonatomic, copy) AFURLConnectionOperationAuthenticationChallengeBlock authenticationChallenge;
@property (readwrite, nonatomic, copy) AFURLConnectionOperationCacheResponseBlock cacheResponse;
@property (readwrite, nonatomic, copy) AFURLConnectionOperationRedirectResponseBlock redirectResponse;
- (void)operationDidStart;
- (void)finish;
- (void)cancelConnection;
@end
@implementation AFURLConnectionOperation
@synthesize outputStream = _outputStream;
+ (void)networkRequestThreadEntryPoint:(id)__unused object {
@autoreleasepool {
[[NSThread currentThread] setName:@"AFNetworking"];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
[runLoop run];
}
}
+ (NSThread *)networkRequestThread {
static NSThread *_networkRequestThread = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
[_networkRequestThread start];
});
return _networkRequestThread;
}
- (instancetype)initWithRequest:(NSURLRequest *)urlRequest {
NSParameterAssert(urlRequest);
self = [super init];
if (!self) {
return nil;
}
_state = AFOperationReadyState;
self.lock = [[NSRecursiveLock alloc] init];
self.lock.name = kAFNetworkingLockName;
self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes];
self.request = urlRequest;
self.shouldUseCredentialStorage = YES;
self.securityPolicy = [AFSecurityPolicy defaultPolicy];
return self;
}
- (instancetype)init NS_UNAVAILABLE
{
return nil;
}
- (void)dealloc {
if (_outputStream) {
[_outputStream close];
_outputStream = nil;
}
if (_backgroundTaskCleanup) {
_backgroundTaskCleanup();
}
}
#pragma mark -
- (void)setResponseData:(NSData *)responseData {
[self.lock lock];
if (!responseData) {
_responseData = nil;
} else {
_responseData = [NSData dataWithBytes:responseData.bytes length:responseData.length];
}
[self.lock unlock];
}
- (NSString *)responseString {
[self.lock lock];
if (!_responseString && self.response && self.responseData) {
self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding];
}
[self.lock unlock];
return _responseString;
}
- (NSStringEncoding)responseStringEncoding {
[self.lock lock];
if (!_responseStringEncoding && self.response) {
NSStringEncoding stringEncoding = NSUTF8StringEncoding;
if (self.response.textEncodingName) {
CFStringEncoding IANAEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)self.response.textEncodingName);
if (IANAEncoding != kCFStringEncodingInvalidId) {
stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding);
}
}
self.responseStringEncoding = stringEncoding;
}
[self.lock unlock];
return _responseStringEncoding;
}
- (NSInputStream *)inputStream {
return self.request.HTTPBodyStream;
}
- (void)setInputStream:(NSInputStream *)inputStream {
NSMutableURLRequest *mutableRequest = [self.request mutableCopy];
mutableRequest.HTTPBodyStream = inputStream;
self.request = mutableRequest;
}
- (NSOutputStream *)outputStream {
if (!_outputStream) {
self.outputStream = [NSOutputStream outputStreamToMemory];
}
return _outputStream;
}
- (void)setOutputStream:(NSOutputStream *)outputStream {
[self.lock lock];
if (outputStream != _outputStream) {
if (_outputStream) {
[_outputStream close];
}
_outputStream = outputStream;
}
[self.lock unlock];
}
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler {
[self.lock lock];
if (!self.backgroundTaskCleanup) {
UIApplication *application = [UIApplication sharedApplication];
UIBackgroundTaskIdentifier __block backgroundTaskIdentifier = UIBackgroundTaskInvalid;
__weak __typeof(self)weakSelf = self;
self.backgroundTaskCleanup = ^(){
if (backgroundTaskIdentifier != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:backgroundTaskIdentifier];
backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}
};
backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
__strong __typeof(weakSelf)strongSelf = weakSelf;
if (handler) {
handler();
}
if (strongSelf) {
[strongSelf cancel];
strongSelf.backgroundTaskCleanup();
}
}];
}
[self.lock unlock];
}
#endif
#pragma mark -
- (void)setState:(AFOperationState)state {
if (!AFStateTransitionIsValid(self.state, state, [self isCancelled])) {
return;
}
[self.lock lock];
NSString *oldStateKey = AFKeyPathFromOperationState(self.state);
NSString *newStateKey = AFKeyPathFromOperationState(state);
[self willChangeValueForKey:newStateKey];
[self willChangeValueForKey:oldStateKey];
_state = state;
[self didChangeValueForKey:oldStateKey];
[self didChangeValueForKey:newStateKey];
[self.lock unlock];
}
- (void)pause {
if ([self isPaused] || [self isFinished] || [self isCancelled]) {
return;
}
[self.lock lock];
if ([self isExecuting]) {
[self performSelector:@selector(operationDidPause) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
dispatch_async(dispatch_get_main_queue(), ^{
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
});
}
self.state = AFOperationPausedState;
[self.lock unlock];
}
- (void)operationDidPause {
[self.lock lock];
[self.connection cancel];
[self.lock unlock];
}
- (BOOL)isPaused {
return self.state == AFOperationPausedState;
}
- (void)resume {
if (![self isPaused]) {
return;
}
[self.lock lock];
self.state = AFOperationReadyState;
[self start];
[self.lock unlock];
}
#pragma mark -
- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block {
self.uploadProgress = block;
}
- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block {
self.downloadProgress = block;
}
- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block {
self.authenticationChallenge = block;
}
- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block {
self.cacheResponse = block;
}
- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block {
self.redirectResponse = block;
}
#pragma mark - NSOperation
- (void)setCompletionBlock:(void (^)(void))block {
[self.lock lock];
if (!block) {
[super setCompletionBlock:nil];
} else {
__weak __typeof(self)weakSelf = self;
[super setCompletionBlock:^ {
__strong __typeof(weakSelf)strongSelf = weakSelf;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_group_t group = strongSelf.completionGroup ?: url_request_operation_completion_group();
dispatch_queue_t queue = strongSelf.completionQueue ?: dispatch_get_main_queue();
#pragma clang diagnostic pop
dispatch_group_async(group, queue, ^{
block();
});
dispatch_group_notify(group, url_request_operation_completion_queue(), ^{
[strongSelf setCompletionBlock:nil];
});
}];
}
[self.lock unlock];
}
- (BOOL)isReady {
return self.state == AFOperationReadyState && [super isReady];
}
- (BOOL)isExecuting {
return self.state == AFOperationExecutingState;
}
- (BOOL)isFinished {
return self.state == AFOperationFinishedState;
}
- (BOOL)isConcurrent {
return YES;
}
- (void)start {
[self.lock lock];
if ([self isCancelled]) {
[self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
} else if ([self isReady]) {
self.state = AFOperationExecutingState;
[self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
}
[self.lock unlock];
}
- (void)operationDidStart {
[self.lock lock];
if (![self isCancelled]) {
self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
for (NSString *runLoopMode in self.runLoopModes) {
[self.connection scheduleInRunLoop:runLoop forMode:runLoopMode];
[self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode];
}
[self.outputStream open];
[self.connection start];
}
[self.lock unlock];
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self];
});
}
- (void)finish {
[self.lock lock];
self.state = AFOperationFinishedState;
[self.lock unlock];
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
});
}
- (void)cancel {
[self.lock lock];
if (![self isFinished] && ![self isCancelled]) {
[super cancel];
if ([self isExecuting]) {
[self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
}
}
[self.lock unlock];
}
- (void)cancelConnection {
NSDictionary *userInfo = nil;
if ([self.request URL]) {
userInfo = @{NSURLErrorFailingURLErrorKey : [self.request URL]};
}
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
if (![self isFinished]) {
if (self.connection) {
[self.connection cancel];
[self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:error];
} else {
// Accommodate race condition where `self.connection` has not yet been set before cancellation
self.error = error;
[self finish];
}
}
}
#pragma mark -
+ (NSArray *)batchOfRequestOperations:(NSArray *)operations
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock
{
if (!operations || [operations count] == 0) {
return @[[NSBlockOperation blockOperationWithBlock:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (completionBlock) {
completionBlock(@[]);
}
});
}]];
}
__block dispatch_group_t group = dispatch_group_create();
NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
if (completionBlock) {
completionBlock(operations);
}
});
}];
for (AFURLConnectionOperation *operation in operations) {
operation.completionGroup = group;
void (^originalCompletionBlock)(void) = [operation.completionBlock copy];
__weak __typeof(operation)weakOperation = operation;
operation.completionBlock = ^{
__strong __typeof(weakOperation)strongOperation = weakOperation;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_queue_t queue = strongOperation.completionQueue ?: dispatch_get_main_queue();
#pragma clang diagnostic pop
dispatch_group_async(group, queue, ^{
if (originalCompletionBlock) {
originalCompletionBlock();
}
NSUInteger numberOfFinishedOperations = [[operations indexesOfObjectsPassingTest:^BOOL(id op, NSUInteger __unused idx, BOOL __unused *stop) {
return [op isFinished];
}] count];
if (progressBlock) {
progressBlock(numberOfFinishedOperations, [operations count]);
}
dispatch_group_leave(group);
});
};
dispatch_group_enter(group);
[batchedOperation addDependency:operation];
}
return [operations arrayByAddingObject:batchedOperation];
}
#pragma mark - NSObject
- (NSString *)description {
[self.lock lock];
NSString *description = [NSString stringWithFormat:@"<%@: %p, state: %@, cancelled: %@ request: %@, response: %@>", NSStringFromClass([self class]), self, AFKeyPathFromOperationState(self.state), ([self isCancelled] ? @"YES" : @"NO"), self.request, self.response];
[self.lock unlock];
return description;
}
#pragma mark - NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection
willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if (self.authenticationChallenge) {
self.authenticationChallenge(connection, challenge);
return;
}
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
} else {
if ([challenge previousFailureCount] == 0) {
if (self.credential) {
[[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
}
} else {
[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
}
}
}
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection {
return self.shouldUseCredentialStorage;
}
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)redirectResponse
{
if (self.redirectResponse) {
return self.redirectResponse(connection, request, redirectResponse);
} else {
return request;
}
}
- (void)connection:(NSURLConnection __unused *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
dispatch_async(dispatch_get_main_queue(), ^{
if (self.uploadProgress) {
self.uploadProgress((NSUInteger)bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}
});
}
- (void)connection:(NSURLConnection __unused *)connection
didReceiveResponse:(NSURLResponse *)response
{
self.response = response;
}
- (void)connection:(NSURLConnection __unused *)connection
didReceiveData:(NSData *)data
{
NSUInteger length = [data length];
while (YES) {
NSInteger totalNumberOfBytesWritten = 0;
if ([self.outputStream hasSpaceAvailable]) {
const uint8_t *dataBuffer = (uint8_t *)[data bytes];
NSInteger numberOfBytesWritten = 0;
while (totalNumberOfBytesWritten < (NSInteger)length) {
numberOfBytesWritten = [self.outputStream write:&dataBuffer[(NSUInteger)totalNumberOfBytesWritten] maxLength:(length - (NSUInteger)totalNumberOfBytesWritten)];
if (numberOfBytesWritten == -1) {
break;
}
totalNumberOfBytesWritten += numberOfBytesWritten;
}
break;
} else {
[self.connection cancel];
if (self.outputStream.streamError) {
[self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.outputStream.streamError];
}
return;
}
}
dispatch_async(dispatch_get_main_queue(), ^{
self.totalBytesRead += (long long)length;
if (self.downloadProgress) {
self.downloadProgress(length, self.totalBytesRead, self.response.expectedContentLength);
}
});
}
- (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection {
self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
[self.outputStream close];
if (self.responseData) {
self.outputStream = nil;
}
self.connection = nil;
[self finish];
}
- (void)connection:(NSURLConnection __unused *)connection
didFailWithError:(NSError *)error
{
self.error = error;
[self.outputStream close];
if (self.responseData) {
self.outputStream = nil;
}
self.connection = nil;
[self finish];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
if (self.cacheResponse) {
return self.cacheResponse(connection, cachedResponse);
} else {
if ([self isCancelled]) {
return nil;
}
return cachedResponse;
}
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (id)initWithCoder:(NSCoder *)decoder {
NSURLRequest *request = [decoder decodeObjectOfClass:[NSURLRequest class] forKey:NSStringFromSelector(@selector(request))];
self = [self initWithRequest:request];
if (!self) {
return nil;
}
self.state = (AFOperationState)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(state))] integerValue];
self.response = [decoder decodeObjectOfClass:[NSHTTPURLResponse class] forKey:NSStringFromSelector(@selector(response))];
self.error = [decoder decodeObjectOfClass:[NSError class] forKey:NSStringFromSelector(@selector(error))];
self.responseData = [decoder decodeObjectOfClass:[NSData class] forKey:NSStringFromSelector(@selector(responseData))];
self.totalBytesRead = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(totalBytesRead))] longLongValue];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[self pause];
[coder encodeObject:self.request forKey:NSStringFromSelector(@selector(request))];
switch (self.state) {
case AFOperationExecutingState:
case AFOperationPausedState:
[coder encodeInteger:AFOperationReadyState forKey:NSStringFromSelector(@selector(state))];
break;
default:
[coder encodeInteger:self.state forKey:NSStringFromSelector(@selector(state))];
break;
}
[coder encodeObject:self.response forKey:NSStringFromSelector(@selector(response))];
[coder encodeObject:self.error forKey:NSStringFromSelector(@selector(error))];
[coder encodeObject:self.responseData forKey:NSStringFromSelector(@selector(responseData))];
[coder encodeInt64:self.totalBytesRead forKey:NSStringFromSelector(@selector(totalBytesRead))];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
AFURLConnectionOperation *operation = [(AFURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request];
operation.uploadProgress = self.uploadProgress;
operation.downloadProgress = self.downloadProgress;
operation.authenticationChallenge = self.authenticationChallenge;
operation.cacheResponse = self.cacheResponse;
operation.redirectResponse = self.redirectResponse;
operation.completionQueue = self.completionQueue;
operation.completionGroup = self.completionGroup;
return operation;
}
@end
// AFURLRequestSerialization.h // AFURLRequestSerialization.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -20,9 +20,7 @@ ...@@ -20,9 +20,7 @@
// THE SOFTWARE. // THE SOFTWARE.
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <TargetConditionals.h> #if TARGET_OS_IOS
#if TARGET_OS_IOS || TARGET_OS_TV
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
#elif TARGET_OS_WATCH #elif TARGET_OS_WATCH
#import <WatchKit/WatchKit.h> #import <WatchKit/WatchKit.h>
...@@ -31,31 +29,6 @@ ...@@ -31,31 +29,6 @@
NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
/** /**
Returns a percent-escaped string following RFC 3986 for a query string key or value.
RFC 3986 states that the following characters are "reserved" characters.
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
should be percent-escaped in the query string.
@param string The string to be percent-escaped.
@return The percent-escaped string.
*/
FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string);
/**
A helper method to generate encoded url query parameters for appending to the end of a URL.
@param parameters A dictionary of key/values to be encoded.
@return A url encoded query string
*/
FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters);
/**
The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary. The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary.
For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`. For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`.
...@@ -73,8 +46,11 @@ FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameter ...@@ -73,8 +46,11 @@ FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameter
*/ */
- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request - (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(nullable id)parameters withParameters:(nullable id)parameters
error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; error:(NSError * __nullable __autoreleasing *)error
#ifdef NS_SWIFT_NOTHROW
NS_SWIFT_NOTHROW
#endif
;
@end @end
#pragma mark - #pragma mark -
...@@ -154,7 +130,7 @@ typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) { ...@@ -154,7 +130,7 @@ typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) {
@discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`. @discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`.
*/ */
@property (readonly, nonatomic, strong) NSDictionary <NSString *, NSString *> *HTTPRequestHeaders; @property (readonly, nonatomic, strong) NSDictionary *HTTPRequestHeaders;
/** /**
Creates and returns a serializer with default configuration. Creates and returns a serializer with default configuration.
...@@ -189,6 +165,12 @@ forHTTPHeaderField:(NSString *)field; ...@@ -189,6 +165,12 @@ forHTTPHeaderField:(NSString *)field;
password:(NSString *)password; password:(NSString *)password;
/** /**
@deprecated This method has been deprecated. Use -setValue:forHTTPHeaderField: instead.
*/
- (void)setAuthorizationHeaderFieldWithToken:(NSString *)token DEPRECATED_ATTRIBUTE;
/**
Clears any existing value for the "Authorization" HTTP header. Clears any existing value for the "Authorization" HTTP header.
*/ */
- (void)clearAuthorizationHeader; - (void)clearAuthorizationHeader;
...@@ -200,7 +182,7 @@ forHTTPHeaderField:(NSString *)field; ...@@ -200,7 +182,7 @@ forHTTPHeaderField:(NSString *)field;
/** /**
HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default. HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default.
*/ */
@property (nonatomic, strong) NSSet <NSString *> *HTTPMethodsEncodingParametersInURI; @property (nonatomic, strong) NSSet *HTTPMethodsEncodingParametersInURI;
/** /**
Set the method of query string serialization according to one of the pre-defined styles. Set the method of query string serialization according to one of the pre-defined styles.
...@@ -223,6 +205,13 @@ forHTTPHeaderField:(NSString *)field; ...@@ -223,6 +205,13 @@ forHTTPHeaderField:(NSString *)field;
///------------------------------- ///-------------------------------
/** /**
@deprecated This method has been deprecated. Use -requestWithMethod:URLString:parameters:error: instead.
*/
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters DEPRECATED_ATTRIBUTE;
/**
Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string. Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string.
If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body. If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body.
...@@ -237,7 +226,15 @@ forHTTPHeaderField:(NSString *)field; ...@@ -237,7 +226,15 @@ forHTTPHeaderField:(NSString *)field;
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method - (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString URLString:(NSString *)URLString
parameters:(nullable id)parameters parameters:(nullable id)parameters
error:(NSError * _Nullable __autoreleasing *)error; error:(NSError * __nullable __autoreleasing *)error;
/**
@deprecated This method has been deprecated. Use -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error: instead.
*/
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block DEPRECATED_ATTRIBUTE;
/** /**
Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2 Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
...@@ -254,9 +251,9 @@ forHTTPHeaderField:(NSString *)field; ...@@ -254,9 +251,9 @@ forHTTPHeaderField:(NSString *)field;
*/ */
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
URLString:(NSString *)URLString URLString:(NSString *)URLString
parameters:(nullable NSDictionary <NSString *, id> *)parameters parameters:(nullable NSDictionary *)parameters
constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
error:(NSError * _Nullable __autoreleasing *)error; error:(NSError * __nullable __autoreleasing *)error;
/** /**
Creates an `NSMutableURLRequest` by removing the `HTTPBodyStream` from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished. Creates an `NSMutableURLRequest` by removing the `HTTPBodyStream` from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished.
...@@ -271,7 +268,7 @@ forHTTPHeaderField:(NSString *)field; ...@@ -271,7 +268,7 @@ forHTTPHeaderField:(NSString *)field;
*/ */
- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request - (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
writingStreamContentsToFile:(NSURL *)fileURL writingStreamContentsToFile:(NSURL *)fileURL
completionHandler:(nullable void (^)(NSError * _Nullable error))handler; completionHandler:(nullable void (^)(NSError * __nullable error))handler;
@end @end
...@@ -295,7 +292,7 @@ forHTTPHeaderField:(NSString *)field; ...@@ -295,7 +292,7 @@ forHTTPHeaderField:(NSString *)field;
*/ */
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL - (BOOL)appendPartWithFileURL:(NSURL *)fileURL
name:(NSString *)name name:(NSString *)name
error:(NSError * _Nullable __autoreleasing *)error; error:(NSError * __nullable __autoreleasing *)error;
/** /**
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
...@@ -312,7 +309,7 @@ forHTTPHeaderField:(NSString *)field; ...@@ -312,7 +309,7 @@ forHTTPHeaderField:(NSString *)field;
name:(NSString *)name name:(NSString *)name
fileName:(NSString *)fileName fileName:(NSString *)fileName
mimeType:(NSString *)mimeType mimeType:(NSString *)mimeType
error:(NSError * _Nullable __autoreleasing *)error; error:(NSError * __nullable __autoreleasing *)error;
/** /**
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary. Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary.
...@@ -359,7 +356,7 @@ forHTTPHeaderField:(NSString *)field; ...@@ -359,7 +356,7 @@ forHTTPHeaderField:(NSString *)field;
@param headers The HTTP headers to be appended to the form data. @param headers The HTTP headers to be appended to the form data.
@param body The data to be encoded and appended to the form data. This parameter must not be `nil`. @param body The data to be encoded and appended to the form data. This parameter must not be `nil`.
*/ */
- (void)appendPartWithHeaders:(nullable NSDictionary <NSString *, NSString *> *)headers - (void)appendPartWithHeaders:(nullable NSDictionary *)headers
body:(NSData *)body; body:(NSData *)body;
/** /**
......
// AFURLRequestSerialization.m // AFURLRequestSerialization.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -21,7 +21,7 @@ ...@@ -21,7 +21,7 @@
#import "AFURLRequestSerialization.h" #import "AFURLRequestSerialization.h"
#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV #if __IPHONE_OS_VERSION_MIN_REQUIRED
#import <MobileCoreServices/MobileCoreServices.h> #import <MobileCoreServices/MobileCoreServices.h>
#else #else
#import <CoreServices/CoreServices.h> #import <CoreServices/CoreServices.h>
...@@ -32,6 +32,35 @@ NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofir ...@@ -32,6 +32,35 @@ NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofir
typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error); typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error);
static NSString * AFBase64EncodedStringFromString(NSString *string) {
NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
NSUInteger length = [data length];
NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t *input = (uint8_t *)[data bytes];
uint8_t *output = (uint8_t *)[mutableData mutableBytes];
for (NSUInteger i = 0; i < length; i += 3) {
NSUInteger value = 0;
for (NSUInteger j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
NSUInteger idx = (i / 3) * 4;
output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F];
output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F];
output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '=';
output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
}
/** /**
Returns a percent-escaped string following RFC 3986 for a query string key or value. Returns a percent-escaped string following RFC 3986 for a query string key or value.
RFC 3986 states that the following characters are "reserved" characters. RFC 3986 states that the following characters are "reserved" characters.
...@@ -44,7 +73,7 @@ typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id ...@@ -44,7 +73,7 @@ typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id
- parameter string: The string to be percent-escaped. - parameter string: The string to be percent-escaped.
- returns: The percent-escaped string. - returns: The percent-escaped string.
*/ */
NSString * AFPercentEscapedStringFromString(NSString *string) { static NSString * AFPercentEscapedStringFromString(NSString *string) {
static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4 static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;="; static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
...@@ -60,7 +89,10 @@ NSString * AFPercentEscapedStringFromString(NSString *string) { ...@@ -60,7 +89,10 @@ NSString * AFPercentEscapedStringFromString(NSString *string) {
NSMutableString *escaped = @"".mutableCopy; NSMutableString *escaped = @"".mutableCopy;
while (index < string.length) { while (index < string.length) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wgnu"
NSUInteger length = MIN(string.length - index, batchSize); NSUInteger length = MIN(string.length - index, batchSize);
#pragma GCC diagnostic pop
NSRange range = NSMakeRange(index, length); NSRange range = NSMakeRange(index, length);
// To avoid breaking up character sequences such as 👴🏻👮🏽 // To avoid breaking up character sequences such as 👴🏻👮🏽
...@@ -82,14 +114,14 @@ NSString * AFPercentEscapedStringFromString(NSString *string) { ...@@ -82,14 +114,14 @@ NSString * AFPercentEscapedStringFromString(NSString *string) {
@property (readwrite, nonatomic, strong) id field; @property (readwrite, nonatomic, strong) id field;
@property (readwrite, nonatomic, strong) id value; @property (readwrite, nonatomic, strong) id value;
- (instancetype)initWithField:(id)field value:(id)value; - (id)initWithField:(id)field value:(id)value;
- (NSString *)URLEncodedStringValue; - (NSString *)URLEncodedStringValue;
@end @end
@implementation AFQueryStringPair @implementation AFQueryStringPair
- (instancetype)initWithField:(id)field value:(id)value { - (id)initWithField:(id)field value:(id)value {
self = [super init]; self = [super init];
if (!self) { if (!self) {
return nil; return nil;
...@@ -116,7 +148,7 @@ NSString * AFPercentEscapedStringFromString(NSString *string) { ...@@ -116,7 +148,7 @@ NSString * AFPercentEscapedStringFromString(NSString *string) {
FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary);
FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value);
NSString * AFQueryStringFromParameters(NSDictionary *parameters) { static NSString * AFQueryStringFromParameters(NSDictionary *parameters) {
NSMutableArray *mutablePairs = [NSMutableArray array]; NSMutableArray *mutablePairs = [NSMutableArray array];
for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
[mutablePairs addObject:[pair URLEncodedStringValue]]; [mutablePairs addObject:[pair URLEncodedStringValue]];
...@@ -186,7 +218,6 @@ static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerOb ...@@ -186,7 +218,6 @@ static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerOb
@interface AFHTTPRequestSerializer () @interface AFHTTPRequestSerializer ()
@property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths; @property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths;
@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders; @property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders;
@property (readwrite, nonatomic, strong) dispatch_queue_t requestHeaderModificationQueue;
@property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle; @property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle;
@property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization; @property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization;
@end @end
...@@ -206,7 +237,6 @@ static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerOb ...@@ -206,7 +237,6 @@ static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerOb
self.stringEncoding = NSUTF8StringEncoding; self.stringEncoding = NSUTF8StringEncoding;
self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary]; self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary];
self.requestHeaderModificationQueue = dispatch_queue_create("requestHeaderModificationQueue", DISPATCH_QUEUE_CONCURRENT);
// Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
NSMutableArray *acceptLanguagesComponents = [NSMutableArray array]; NSMutableArray *acceptLanguagesComponents = [NSMutableArray array];
...@@ -218,6 +248,8 @@ static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerOb ...@@ -218,6 +248,8 @@ static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerOb
[self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"]; [self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"];
NSString *userAgent = nil; NSString *userAgent = nil;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
#if TARGET_OS_IOS #if TARGET_OS_IOS
// User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]];
...@@ -227,6 +259,7 @@ static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerOb ...@@ -227,6 +259,7 @@ static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerOb
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]; userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]];
#endif #endif
#pragma clang diagnostic pop
if (userAgent) { if (userAgent) {
if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) { if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) {
NSMutableString *mutableUserAgent = [userAgent mutableCopy]; NSMutableString *mutableUserAgent = [userAgent mutableCopy];
...@@ -302,41 +335,32 @@ static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerOb ...@@ -302,41 +335,32 @@ static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerOb
#pragma mark - #pragma mark -
- (NSDictionary *)HTTPRequestHeaders { - (NSDictionary *)HTTPRequestHeaders {
NSDictionary __block *value; return [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders];
dispatch_sync(self.requestHeaderModificationQueue, ^{
value = [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders];
});
return value;
} }
- (void)setValue:(NSString *)value - (void)setValue:(NSString *)value
forHTTPHeaderField:(NSString *)field forHTTPHeaderField:(NSString *)field
{ {
dispatch_barrier_async(self.requestHeaderModificationQueue, ^{ [self.mutableHTTPRequestHeaders setValue:value forKey:field];
[self.mutableHTTPRequestHeaders setValue:value forKey:field];
});
} }
- (NSString *)valueForHTTPHeaderField:(NSString *)field { - (NSString *)valueForHTTPHeaderField:(NSString *)field {
NSString __block *value; return [self.mutableHTTPRequestHeaders valueForKey:field];
dispatch_sync(self.requestHeaderModificationQueue, ^{
value = [self.mutableHTTPRequestHeaders valueForKey:field];
});
return value;
} }
- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username - (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
password:(NSString *)password password:(NSString *)password
{ {
NSData *basicAuthCredentials = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding]; NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password];
NSString *base64AuthCredentials = [basicAuthCredentials base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0]; [self setValue:[NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)] forHTTPHeaderField:@"Authorization"];
[self setValue:[NSString stringWithFormat:@"Basic %@", base64AuthCredentials] forHTTPHeaderField:@"Authorization"]; }
- (void)setAuthorizationHeaderFieldWithToken:(NSString *)token {
[self setValue:[NSString stringWithFormat:@"Token token=\"%@\"", token] forHTTPHeaderField:@"Authorization"];
} }
- (void)clearAuthorizationHeader { - (void)clearAuthorizationHeader {
dispatch_barrier_async(self.requestHeaderModificationQueue, ^{ [self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"];
[self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"];
});
} }
#pragma mark - #pragma mark -
...@@ -355,6 +379,13 @@ forHTTPHeaderField:(NSString *)field ...@@ -355,6 +379,13 @@ forHTTPHeaderField:(NSString *)field
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method - (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString URLString:(NSString *)URLString
parameters:(id)parameters parameters:(id)parameters
{
return [self requestWithMethod:method URLString:URLString parameters:parameters error:nil];
}
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
error:(NSError *__autoreleasing *)error error:(NSError *__autoreleasing *)error
{ {
NSParameterAssert(method); NSParameterAssert(method);
...@@ -382,6 +413,14 @@ forHTTPHeaderField:(NSString *)field ...@@ -382,6 +413,14 @@ forHTTPHeaderField:(NSString *)field
URLString:(NSString *)URLString URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters parameters:(NSDictionary *)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
{
return [self multipartFormRequestWithMethod:method URLString:URLString parameters:parameters constructingBodyWithBlock:block error:nil];
}
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
error:(NSError *__autoreleasing *)error error:(NSError *__autoreleasing *)error
{ {
NSParameterAssert(method); NSParameterAssert(method);
...@@ -508,7 +547,7 @@ forHTTPHeaderField:(NSString *)field ...@@ -508,7 +547,7 @@ forHTTPHeaderField:(NSString *)field
} }
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
if (query && query.length > 0) { if (query) {
mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]]; mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]];
} }
} else { } else {
...@@ -555,7 +594,7 @@ forHTTPHeaderField:(NSString *)field ...@@ -555,7 +594,7 @@ forHTTPHeaderField:(NSString *)field
return YES; return YES;
} }
- (instancetype)initWithCoder:(NSCoder *)decoder { - (id)initWithCoder:(NSCoder *)decoder {
self = [self init]; self = [self init];
if (!self) { if (!self) {
return nil; return nil;
...@@ -568,19 +607,15 @@ forHTTPHeaderField:(NSString *)field ...@@ -568,19 +607,15 @@ forHTTPHeaderField:(NSString *)field
} }
- (void)encodeWithCoder:(NSCoder *)coder { - (void)encodeWithCoder:(NSCoder *)coder {
dispatch_sync(self.requestHeaderModificationQueue, ^{ [coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))];
[coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))];
});
[coder encodeInteger:self.queryStringSerializationStyle forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))]; [coder encodeInteger:self.queryStringSerializationStyle forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))];
} }
#pragma mark - NSCopying #pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone { - (id)copyWithZone:(NSZone *)zone {
AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init]; AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init];
dispatch_sync(self.requestHeaderModificationQueue, ^{ serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone];
serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone];
});
serializer.queryStringSerializationStyle = self.queryStringSerializationStyle; serializer.queryStringSerializationStyle = self.queryStringSerializationStyle;
serializer.queryStringSerialization = self.queryStringSerialization; serializer.queryStringSerialization = self.queryStringSerialization;
...@@ -610,6 +645,7 @@ static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) { ...@@ -610,6 +645,7 @@ static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) {
} }
static inline NSString * AFContentTypeForPathExtension(NSString *extension) { static inline NSString * AFContentTypeForPathExtension(NSString *extension) {
#ifdef __UTTYPE__
NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL); NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL);
NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType); NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
if (!contentType) { if (!contentType) {
...@@ -617,6 +653,10 @@ static inline NSString * AFContentTypeForPathExtension(NSString *extension) { ...@@ -617,6 +653,10 @@ static inline NSString * AFContentTypeForPathExtension(NSString *extension) {
} else { } else {
return contentType; return contentType;
} }
#else
#pragma unused (extension)
return @"application/octet-stream";
#endif
} }
NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16; NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16;
...@@ -647,7 +687,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; ...@@ -647,7 +687,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
@property (readonly, nonatomic, assign) unsigned long long contentLength; @property (readonly, nonatomic, assign) unsigned long long contentLength;
@property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty; @property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty;
- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding; - (id)initWithStringEncoding:(NSStringEncoding)encoding;
- (void)setInitialAndFinalBoundaries; - (void)setInitialAndFinalBoundaries;
- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart; - (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart;
@end @end
...@@ -663,8 +703,8 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; ...@@ -663,8 +703,8 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
@implementation AFStreamingMultipartFormData @implementation AFStreamingMultipartFormData
- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest - (id)initWithURLRequest:(NSMutableURLRequest *)urlRequest
stringEncoding:(NSStringEncoding)encoding stringEncoding:(NSStringEncoding)encoding
{ {
self = [super init]; self = [super init];
if (!self) { if (!self) {
...@@ -679,11 +719,6 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; ...@@ -679,11 +719,6 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
return self; return self;
} }
- (void)setRequest:(NSMutableURLRequest *)request
{
_request = [request mutableCopy];
}
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL - (BOOL)appendPartWithFileURL:(NSURL *)fileURL
name:(NSString *)name name:(NSString *)name
error:(NSError * __autoreleasing *)error error:(NSError * __autoreleasing *)error
...@@ -852,13 +887,16 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; ...@@ -852,13 +887,16 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
@end @end
@implementation AFMultipartBodyStream @implementation AFMultipartBodyStream
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wimplicit-atomic-properties"
#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1100) #if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1100)
@synthesize delegate; @synthesize delegate;
#endif #endif
@synthesize streamStatus; @synthesize streamStatus;
@synthesize streamError; @synthesize streamError;
#pragma clang diagnostic pop
- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding { - (id)initWithStringEncoding:(NSStringEncoding)encoding {
self = [super init]; self = [super init];
if (!self) { if (!self) {
return nil; return nil;
...@@ -902,13 +940,15 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; ...@@ -902,13 +940,15 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
NSInteger totalNumberOfBytesRead = 0; NSInteger totalNumberOfBytesRead = 0;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) { while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) {
if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) { if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) {
if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) { if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) {
break; break;
} }
} else { } else {
NSUInteger maxLength = MIN(length, self.numberOfBytesInPacket) - (NSUInteger)totalNumberOfBytesRead; NSUInteger maxLength = length - (NSUInteger)totalNumberOfBytesRead;
NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength]; NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength];
if (numberOfBytesRead == -1) { if (numberOfBytesRead == -1) {
self.streamError = self.currentHTTPBodyPart.inputStream.streamError; self.streamError = self.currentHTTPBodyPart.inputStream.streamError;
...@@ -922,6 +962,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; ...@@ -922,6 +962,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
} }
} }
} }
#pragma clang diagnostic pop
return totalNumberOfBytesRead; return totalNumberOfBytesRead;
} }
...@@ -998,7 +1039,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; ...@@ -998,7 +1039,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
#pragma mark - NSCopying #pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone { -(id)copyWithZone:(NSZone *)zone {
AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding]; AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding];
for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
...@@ -1035,7 +1076,7 @@ typedef enum { ...@@ -1035,7 +1076,7 @@ typedef enum {
@implementation AFHTTPBodyPart @implementation AFHTTPBodyPart
- (instancetype)init { - (id)init {
self = [super init]; self = [super init];
if (!self) { if (!self) {
return nil; return nil;
...@@ -1102,6 +1143,8 @@ typedef enum { ...@@ -1102,6 +1143,8 @@ typedef enum {
return YES; return YES;
} }
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcovered-switch-default"
switch (self.inputStream.streamStatus) { switch (self.inputStream.streamStatus) {
case NSStreamStatusNotOpen: case NSStreamStatusNotOpen:
case NSStreamStatusOpening: case NSStreamStatusOpening:
...@@ -1115,6 +1158,7 @@ typedef enum { ...@@ -1115,6 +1158,7 @@ typedef enum {
default: default:
return NO; return NO;
} }
#pragma clang diagnostic pop
} }
- (NSInteger)read:(uint8_t *)buffer - (NSInteger)read:(uint8_t *)buffer
...@@ -1159,8 +1203,11 @@ typedef enum { ...@@ -1159,8 +1203,11 @@ typedef enum {
intoBuffer:(uint8_t *)buffer intoBuffer:(uint8_t *)buffer
maxLength:(NSUInteger)length maxLength:(NSUInteger)length
{ {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length)); NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length));
[data getBytes:buffer range:range]; [data getBytes:buffer range:range];
#pragma clang diagnostic pop
_phaseReadOffset += range.length; _phaseReadOffset += range.length;
...@@ -1179,6 +1226,8 @@ typedef enum { ...@@ -1179,6 +1226,8 @@ typedef enum {
return YES; return YES;
} }
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcovered-switch-default"
switch (_phase) { switch (_phase) {
case AFEncapsulationBoundaryPhase: case AFEncapsulationBoundaryPhase:
_phase = AFHeaderPhase; _phase = AFHeaderPhase;
...@@ -1198,13 +1247,14 @@ typedef enum { ...@@ -1198,13 +1247,14 @@ typedef enum {
break; break;
} }
_phaseReadOffset = 0; _phaseReadOffset = 0;
#pragma clang diagnostic pop
return YES; return YES;
} }
#pragma mark - NSCopying #pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone { - (id)copyWithZone:(NSZone *)zone {
AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init]; AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init];
bodyPart.stringEncoding = self.stringEncoding; bodyPart.stringEncoding = self.stringEncoding;
...@@ -1259,21 +1309,7 @@ typedef enum { ...@@ -1259,21 +1309,7 @@ typedef enum {
[mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
} }
if (![NSJSONSerialization isValidJSONObject:parameters]) { [mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]];
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;
}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error];
if (!jsonData) {
return nil;
}
[mutableRequest setHTTPBody:jsonData];
} }
return mutableRequest; return mutableRequest;
...@@ -1281,7 +1317,7 @@ typedef enum { ...@@ -1281,7 +1317,7 @@ typedef enum {
#pragma mark - NSSecureCoding #pragma mark - NSSecureCoding
- (instancetype)initWithCoder:(NSCoder *)decoder { - (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder]; self = [super initWithCoder:decoder];
if (!self) { if (!self) {
return nil; return nil;
...@@ -1300,7 +1336,7 @@ typedef enum { ...@@ -1300,7 +1336,7 @@ typedef enum {
#pragma mark - NSCopying #pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone { - (id)copyWithZone:(NSZone *)zone {
AFJSONRequestSerializer *serializer = [super copyWithZone:zone]; AFJSONRequestSerializer *serializer = [super copyWithZone:zone];
serializer.writingOptions = self.writingOptions; serializer.writingOptions = self.writingOptions;
...@@ -1352,13 +1388,7 @@ typedef enum { ...@@ -1352,13 +1388,7 @@ typedef enum {
[mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"]; [mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"];
} }
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error]; [mutableRequest setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error]];
if (!plistData) {
return nil;
}
[mutableRequest setHTTPBody:plistData];
} }
return mutableRequest; return mutableRequest;
...@@ -1366,7 +1396,7 @@ typedef enum { ...@@ -1366,7 +1396,7 @@ typedef enum {
#pragma mark - NSSecureCoding #pragma mark - NSSecureCoding
- (instancetype)initWithCoder:(NSCoder *)decoder { - (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder]; self = [super initWithCoder:decoder];
if (!self) { if (!self) {
return nil; return nil;
...@@ -1387,7 +1417,7 @@ typedef enum { ...@@ -1387,7 +1417,7 @@ typedef enum {
#pragma mark - NSCopying #pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone { - (id)copyWithZone:(NSZone *)zone {
AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone]; AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone];
serializer.format = self.format; serializer.format = self.format;
serializer.writeOptions = self.writeOptions; serializer.writeOptions = self.writeOptions;
......
// AFURLResponseSerialization.h // AFURLResponseSerialization.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -42,7 +42,11 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -42,7 +42,11 @@ NS_ASSUME_NONNULL_BEGIN
*/ */
- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response - (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response
data:(nullable NSData *)data data:(nullable NSData *)data
error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; error:(NSError * __nullable __autoreleasing *)error
#ifdef NS_SWIFT_NOTHROW
NS_SWIFT_NOTHROW
#endif
;
@end @end
...@@ -57,7 +61,10 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -57,7 +61,10 @@ NS_ASSUME_NONNULL_BEGIN
- (instancetype)init; - (instancetype)init;
@property (nonatomic, assign) NSStringEncoding stringEncoding DEPRECATED_MSG_ATTRIBUTE("The string encoding is never used. AFHTTPResponseSerializer only validates status codes and content types but does not try to decode the received data in any way."); /**
The string encoding used to serialize data received from the server, when no string encoding is specified by the response. `NSUTF8StringEncoding` by default.
*/
@property (nonatomic, assign) NSStringEncoding stringEncoding;
/** /**
Creates and returns a serializer with default configuration. Creates and returns a serializer with default configuration.
...@@ -78,7 +85,7 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -78,7 +85,7 @@ NS_ASSUME_NONNULL_BEGIN
/** /**
The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation. The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation.
*/ */
@property (nonatomic, copy, nullable) NSSet <NSString *> *acceptableContentTypes; @property (nonatomic, copy, nullable) NSSet *acceptableContentTypes;
/** /**
Validates the specified response and data. Validates the specified response and data.
...@@ -93,7 +100,7 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -93,7 +100,7 @@ NS_ASSUME_NONNULL_BEGIN
*/ */
- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response - (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response
data:(nullable NSData *)data data:(nullable NSData *)data
error:(NSError * _Nullable __autoreleasing *)error; error:(NSError * __nullable __autoreleasing *)error;
@end @end
...@@ -108,8 +115,6 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -108,8 +115,6 @@ NS_ASSUME_NONNULL_BEGIN
- `application/json` - `application/json`
- `text/json` - `text/json`
- `text/javascript` - `text/javascript`
In RFC 7159 - Section 8.1, it states that JSON text is required to be encoded in UTF-8, UTF-16, or UTF-32, and the default encoding is UTF-8. NSJSONSerialization provides support for all the encodings listed in the specification, and recommends UTF-8 for efficiency. Using an unsupported encoding will result in serialization error. See the `NSJSONSerialization` documentation for more details.
*/ */
@interface AFJSONResponseSerializer : AFHTTPResponseSerializer @interface AFJSONResponseSerializer : AFHTTPResponseSerializer
...@@ -165,7 +170,7 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -165,7 +170,7 @@ NS_ASSUME_NONNULL_BEGIN
- (instancetype)init; - (instancetype)init;
/** /**
Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSXMLDocument` documentation section "Input and Output Options". `0` by default. Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
*/ */
@property (nonatomic, assign) NSUInteger options; @property (nonatomic, assign) NSUInteger options;
...@@ -234,7 +239,7 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -234,7 +239,7 @@ NS_ASSUME_NONNULL_BEGIN
*/ */
@interface AFImageResponseSerializer : AFHTTPResponseSerializer @interface AFImageResponseSerializer : AFHTTPResponseSerializer
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
/** /**
The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance.
*/ */
...@@ -258,14 +263,14 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -258,14 +263,14 @@ NS_ASSUME_NONNULL_BEGIN
/** /**
The component response serializers. The component response serializers.
*/ */
@property (readonly, nonatomic, copy) NSArray <id<AFURLResponseSerialization>> *responseSerializers; @property (readonly, nonatomic, copy) NSArray *responseSerializers;
/** /**
Creates and returns a compound serializer comprised of the specified response serializers. Creates and returns a compound serializer comprised of the specified response serializers.
@warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`. @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`.
*/ */
+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray <id<AFURLResponseSerialization>> *)responseSerializers; + (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers;
@end @end
......
// AFURLResponseSerialization.m // AFURLResponseSerialization.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -21,8 +21,6 @@ ...@@ -21,8 +21,6 @@
#import "AFURLResponseSerialization.h" #import "AFURLResponseSerialization.h"
#import <TargetConditionals.h>
#if TARGET_OS_IOS #if TARGET_OS_IOS
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
#elif TARGET_OS_WATCH #elif TARGET_OS_WATCH
...@@ -97,6 +95,8 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO ...@@ -97,6 +95,8 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
return nil; return nil;
} }
self.stringEncoding = NSUTF8StringEncoding;
self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
self.acceptableContentTypes = nil; self.acceptableContentTypes = nil;
...@@ -113,9 +113,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO ...@@ -113,9 +113,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
NSError *validationError = nil; NSError *validationError = nil;
if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) { if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) {
if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]] && if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]]) {
!([response MIMEType] == nil && [data length] == 0)) {
if ([data length] > 0 && [response URL]) { if ([data length] > 0 && [response URL]) {
NSMutableDictionary *mutableUserInfo = [@{ NSMutableDictionary *mutableUserInfo = [@{
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]], NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]],
...@@ -173,7 +171,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO ...@@ -173,7 +171,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
return YES; return YES;
} }
- (instancetype)initWithCoder:(NSCoder *)decoder { - (id)initWithCoder:(NSCoder *)decoder {
self = [self init]; self = [self init];
if (!self) { if (!self) {
return nil; return nil;
...@@ -192,7 +190,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO ...@@ -192,7 +190,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
#pragma mark - NSCopying #pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone { - (id)copyWithZone:(NSZone *)zone {
AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone]; serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone];
serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone]; serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone];
...@@ -223,7 +221,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO ...@@ -223,7 +221,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
return nil; return nil;
} }
self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil]; self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
return self; return self;
} }
...@@ -242,26 +240,46 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO ...@@ -242,26 +240,46 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
// Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization. // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization.
// See https://github.com/rails/rails/issues/1742 // See https://github.com/rails/rails/issues/1742
BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]]; NSStringEncoding stringEncoding = self.stringEncoding;
if (response.textEncodingName) {
if (data.length == 0 || isSpace) { CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
return nil; if (encoding != kCFStringEncodingInvalidId) {
stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
}
} }
id responseObject = nil;
NSError *serializationError = nil; NSError *serializationError = nil;
@autoreleasepool {
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError]; NSString *responseString = [[NSString alloc] initWithData:data encoding:stringEncoding];
if (responseString && ![responseString isEqualToString:@" "]) {
// Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character
// See http://stackoverflow.com/a/12843465/157142
data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
if (!responseObject) if (data) {
{ if ([data length] > 0) {
if (error) { responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
*error = AFErrorWithUnderlyingError(serializationError, *error); } else {
return nil;
}
} else {
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: NSLocalizedStringFromTable(@"Data failed decoding as a UTF-8 string", @"AFNetworking", nil),
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Could not decode string: %@", @"AFNetworking", nil), responseString]
};
serializationError = [NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
}
} }
return nil;
} }
if (self.removesKeysWithNullValues) { if (self.removesKeysWithNullValues && responseObject) {
return AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions); responseObject = AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions);
}
if (error) {
*error = AFErrorWithUnderlyingError(serializationError, *error);
} }
return responseObject; return responseObject;
...@@ -269,7 +287,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO ...@@ -269,7 +287,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
#pragma mark - NSSecureCoding #pragma mark - NSSecureCoding
- (instancetype)initWithCoder:(NSCoder *)decoder { - (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder]; self = [super initWithCoder:decoder];
if (!self) { if (!self) {
return nil; return nil;
...@@ -290,8 +308,8 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO ...@@ -290,8 +308,8 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
#pragma mark - NSCopying #pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone { - (id)copyWithZone:(NSZone *)zone {
AFJSONResponseSerializer *serializer = [super copyWithZone:zone]; AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
serializer.readingOptions = self.readingOptions; serializer.readingOptions = self.readingOptions;
serializer.removesKeysWithNullValues = self.removesKeysWithNullValues; serializer.removesKeysWithNullValues = self.removesKeysWithNullValues;
...@@ -381,20 +399,16 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO ...@@ -381,20 +399,16 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
NSError *serializationError = nil; NSError *serializationError = nil;
NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError]; NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError];
if (!document) if (error) {
{ *error = AFErrorWithUnderlyingError(serializationError, *error);
if (error) {
*error = AFErrorWithUnderlyingError(serializationError, *error);
}
return nil;
} }
return document; return document;
} }
#pragma mark - NSSecureCoding #pragma mark - NSSecureCoding
- (instancetype)initWithCoder:(NSCoder *)decoder { - (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder]; self = [super initWithCoder:decoder];
if (!self) { if (!self) {
return nil; return nil;
...@@ -413,8 +427,8 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO ...@@ -413,8 +427,8 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
#pragma mark - NSCopying #pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone { - (id)copyWithZone:(NSZone *)zone {
AFXMLDocumentResponseSerializer *serializer = [super copyWithZone:zone]; AFXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
serializer.options = self.options; serializer.options = self.options;
return serializer; return serializer;
...@@ -465,20 +479,15 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO ...@@ -465,20 +479,15 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
} }
} }
if (!data) { id responseObject;
return nil;
}
NSError *serializationError = nil; NSError *serializationError = nil;
id responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError]; if (data) {
responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError];
if (!responseObject) }
{
if (error) { if (error) {
*error = AFErrorWithUnderlyingError(serializationError, *error); *error = AFErrorWithUnderlyingError(serializationError, *error);
}
return nil;
} }
return responseObject; return responseObject;
...@@ -486,7 +495,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO ...@@ -486,7 +495,7 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
#pragma mark - NSSecureCoding #pragma mark - NSSecureCoding
- (instancetype)initWithCoder:(NSCoder *)decoder { - (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder]; self = [super initWithCoder:decoder];
if (!self) { if (!self) {
return nil; return nil;
...@@ -507,8 +516,8 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO ...@@ -507,8 +516,8 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
#pragma mark - NSCopying #pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone { - (id)copyWithZone:(NSZone *)zone {
AFPropertyListResponseSerializer *serializer = [super copyWithZone:zone]; AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
serializer.format = self.format; serializer.format = self.format;
serializer.readOptions = self.readOptions; serializer.readOptions = self.readOptions;
...@@ -519,9 +528,8 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO ...@@ -519,9 +528,8 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO
#pragma mark - #pragma mark -
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <CoreGraphics/CoreGraphics.h> #import <CoreGraphics/CoreGraphics.h>
#import <UIKit/UIKit.h>
@interface UIImage (AFNetworkingSafeImageLoading) @interface UIImage (AFNetworkingSafeImageLoading)
+ (UIImage *)af_safeImageWithData:(NSData *)data; + (UIImage *)af_safeImageWithData:(NSData *)data;
...@@ -659,10 +667,10 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r ...@@ -659,10 +667,10 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
#if TARGET_OS_IOS || TARGET_OS_TV #if TARGET_OS_IOS
self.imageScale = [[UIScreen mainScreen] scale]; self.imageScale = [[UIScreen mainScreen] scale];
self.automaticallyInflatesResponseImage = YES; self.automaticallyInflatesResponseImage = YES;
#elif TARGET_OS_WATCH #elif TARGET_OS_WATCH
self.imageScale = [[WKInterfaceDevice currentDevice] screenScale]; self.imageScale = [[WKInterfaceDevice currentDevice] screenScale];
self.automaticallyInflatesResponseImage = YES; self.automaticallyInflatesResponseImage = YES;
#endif #endif
...@@ -682,13 +690,13 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r ...@@ -682,13 +690,13 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r
} }
} }
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
if (self.automaticallyInflatesResponseImage) { if (self.automaticallyInflatesResponseImage) {
return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale); return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale);
} else { } else {
return AFImageWithDataAtScale(data, self.imageScale); return AFImageWithDataAtScale(data, self.imageScale);
} }
#else #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
// Ensure that the image is set to it's correct pixel width and height // Ensure that the image is set to it's correct pixel width and height
NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data]; NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data];
NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])]; NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
...@@ -702,13 +710,13 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r ...@@ -702,13 +710,13 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r
#pragma mark - NSSecureCoding #pragma mark - NSSecureCoding
- (instancetype)initWithCoder:(NSCoder *)decoder { - (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder]; self = [super initWithCoder:decoder];
if (!self) { if (!self) {
return nil; return nil;
} }
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))]; NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))];
#if CGFLOAT_IS_DOUBLE #if CGFLOAT_IS_DOUBLE
self.imageScale = [imageScale doubleValue]; self.imageScale = [imageScale doubleValue];
...@@ -725,7 +733,7 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r ...@@ -725,7 +733,7 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r
- (void)encodeWithCoder:(NSCoder *)coder { - (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder]; [super encodeWithCoder:coder];
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
[coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))]; [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))];
[coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
#endif #endif
...@@ -733,10 +741,10 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r ...@@ -733,10 +741,10 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r
#pragma mark - NSCopying #pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone { - (id)copyWithZone:(NSZone *)zone {
AFImageResponseSerializer *serializer = [super copyWithZone:zone]; AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
serializer.imageScale = self.imageScale; serializer.imageScale = self.imageScale;
serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage; serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage;
#endif #endif
...@@ -788,7 +796,7 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r ...@@ -788,7 +796,7 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r
#pragma mark - NSSecureCoding #pragma mark - NSSecureCoding
- (instancetype)initWithCoder:(NSCoder *)decoder { - (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder]; self = [super initWithCoder:decoder];
if (!self) { if (!self) {
return nil; return nil;
...@@ -807,8 +815,8 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r ...@@ -807,8 +815,8 @@ static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *r
#pragma mark - NSCopying #pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone { - (id)copyWithZone:(NSZone *)zone {
AFCompoundResponseSerializer *serializer = [super copyWithZone:zone]; AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
serializer.responseSerializers = self.responseSerializers; serializer.responseSerializers = self.responseSerializers;
return serializer; return serializer;
......
// AFURLSessionManager.h // AFURLSessionManager.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -19,17 +19,23 @@ ...@@ -19,17 +19,23 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import "AFURLResponseSerialization.h" #import "AFURLResponseSerialization.h"
#import "AFURLRequestSerialization.h" #import "AFURLRequestSerialization.h"
#import "AFSecurityPolicy.h" #import "AFSecurityPolicy.h"
#import "AFCompatibilityMacros.h"
#if !TARGET_OS_WATCH #if !TARGET_OS_WATCH
#import "AFNetworkReachabilityManager.h" #import "AFNetworkReachabilityManager.h"
#endif #endif
#ifndef NS_DESIGNATED_INITIALIZER
#if __has_attribute(objc_designated_initializer)
#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
#else
#define NS_DESIGNATED_INITIALIZER
#endif
#endif
/** /**
`AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`. `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
...@@ -52,7 +58,6 @@ ...@@ -52,7 +58,6 @@
- `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:` - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`
- `URLSession:task:didReceiveChallenge:completionHandler:` - `URLSession:task:didReceiveChallenge:completionHandler:`
- `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:` - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`
- `URLSession:task:needNewBodyStream:`
- `URLSession:task:didCompleteWithError:` - `URLSession:task:didCompleteWithError:`
### `NSURLSessionDataDelegate` ### `NSURLSessionDataDelegate`
...@@ -88,6 +93,8 @@ ...@@ -88,6 +93,8 @@
NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || TARGET_OS_WATCH
@interface AFURLSessionManager : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying> @interface AFURLSessionManager : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying>
/** /**
...@@ -112,7 +119,7 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -112,7 +119,7 @@ NS_ASSUME_NONNULL_BEGIN
///------------------------------- ///-------------------------------
/** /**
The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. The security policy used by created request operations to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified.
*/ */
@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; @property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
...@@ -134,22 +141,22 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -134,22 +141,22 @@ NS_ASSUME_NONNULL_BEGIN
/** /**
The data, upload, and download tasks currently run by the managed session. The data, upload, and download tasks currently run by the managed session.
*/ */
@property (readonly, nonatomic, strong) NSArray <NSURLSessionTask *> *tasks; @property (readonly, nonatomic, strong) NSArray *tasks;
/** /**
The data tasks currently run by the managed session. The data tasks currently run by the managed session.
*/ */
@property (readonly, nonatomic, strong) NSArray <NSURLSessionDataTask *> *dataTasks; @property (readonly, nonatomic, strong) NSArray *dataTasks;
/** /**
The upload tasks currently run by the managed session. The upload tasks currently run by the managed session.
*/ */
@property (readonly, nonatomic, strong) NSArray <NSURLSessionUploadTask *> *uploadTasks; @property (readonly, nonatomic, strong) NSArray *uploadTasks;
/** /**
The download tasks currently run by the managed session. The download tasks currently run by the managed session.
*/ */
@property (readonly, nonatomic, strong) NSArray <NSURLSessionDownloadTask *> *downloadTasks; @property (readonly, nonatomic, strong) NSArray *downloadTasks;
///------------------------------- ///-------------------------------
/// @name Managing Callback Queues /// @name Managing Callback Queues
...@@ -158,12 +165,20 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -158,12 +165,20 @@ NS_ASSUME_NONNULL_BEGIN
/** /**
The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
*/ */
#if OS_OBJECT_USE_OBJC
@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; @property (nonatomic, strong, nullable) dispatch_queue_t completionQueue;
#else
@property (nonatomic, assign, nullable) dispatch_queue_t completionQueue;
#endif
/** /**
The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
*/ */
#if OS_OBJECT_USE_OBJC
@property (nonatomic, strong, nullable) dispatch_group_t completionGroup; @property (nonatomic, strong, nullable) dispatch_group_t completionGroup;
#else
@property (nonatomic, assign, nullable) dispatch_group_t completionGroup;
#endif
///--------------------------------- ///---------------------------------
/// @name Working Around System Bugs /// @name Working Around System Bugs
...@@ -209,20 +224,7 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -209,20 +224,7 @@ NS_ASSUME_NONNULL_BEGIN
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
*/ */
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler DEPRECATED_ATTRIBUTE; completionHandler:(nullable void (^)(NSURLResponse *response, id __nullable responseObject, NSError * __nullable error))completionHandler;
/**
Creates an `NSURLSessionDataTask` with the specified request.
@param request The HTTP request for the request.
@param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
@param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
*/
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
///--------------------------- ///---------------------------
/// @name Running Upload Tasks /// @name Running Upload Tasks
...@@ -233,39 +235,39 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -233,39 +235,39 @@ NS_ASSUME_NONNULL_BEGIN
@param request The HTTP request for the request. @param request The HTTP request for the request.
@param fileURL A URL to the local file to be uploaded. @param fileURL A URL to the local file to be uploaded.
@param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. @param progress A progress object monitoring the current upload progress.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
@see `attemptsToRecreateUploadTasksForBackgroundSessions` @see `attemptsToRecreateUploadTasksForBackgroundSessions`
*/ */
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromFile:(NSURL *)fileURL fromFile:(NSURL *)fileURL
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock progress:(NSProgress * __nullable __autoreleasing * __nullable)progress
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; completionHandler:(nullable void (^)(NSURLResponse *response, id __nullable responseObject, NSError * __nullable error))completionHandler;
/** /**
Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body. Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body.
@param request The HTTP request for the request. @param request The HTTP request for the request.
@param bodyData A data object containing the HTTP body to be uploaded. @param bodyData A data object containing the HTTP body to be uploaded.
@param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. @param progress A progress object monitoring the current upload progress.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
*/ */
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromData:(nullable NSData *)bodyData fromData:(nullable NSData *)bodyData
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock progress:(NSProgress * __nullable __autoreleasing * __nullable)progress
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; completionHandler:(nullable void (^)(NSURLResponse *response, id __nullable responseObject, NSError * __nullable error))completionHandler;
/** /**
Creates an `NSURLSessionUploadTask` with the specified streaming request. Creates an `NSURLSessionUploadTask` with the specified streaming request.
@param request The HTTP request for the request. @param request The HTTP request for the request.
@param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. @param progress A progress object monitoring the current upload progress.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
*/ */
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request - (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock progress:(NSProgress * __nullable __autoreleasing * __nullable)progress
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; completionHandler:(nullable void (^)(NSURLResponse *response, id __nullable responseObject, NSError * __nullable error))completionHandler;
///----------------------------- ///-----------------------------
/// @name Running Download Tasks /// @name Running Download Tasks
...@@ -275,29 +277,29 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -275,29 +277,29 @@ NS_ASSUME_NONNULL_BEGIN
Creates an `NSURLSessionDownloadTask` with the specified request. Creates an `NSURLSessionDownloadTask` with the specified request.
@param request The HTTP request for the request. @param request The HTTP request for the request.
@param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. @param progress A progress object monitoring the current download progress.
@param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
@param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
@warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method. @warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method.
*/ */
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock progress:(NSProgress * __nullable __autoreleasing * __nullable)progress
destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * __nullable filePath, NSError * __nullable error))completionHandler;
/** /**
Creates an `NSURLSessionDownloadTask` with the specified resume data. Creates an `NSURLSessionDownloadTask` with the specified resume data.
@param resumeData The data used to resume downloading. @param resumeData The data used to resume downloading.
@param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. @param progress A progress object monitoring the current download progress.
@param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
@param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
*/ */
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock progress:(NSProgress * __nullable __autoreleasing * __nullable)progress
destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * __nullable filePath, NSError * __nullable error))completionHandler;
///--------------------------------- ///---------------------------------
/// @name Getting Progress for Tasks /// @name Getting Progress for Tasks
...@@ -306,20 +308,20 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -306,20 +308,20 @@ NS_ASSUME_NONNULL_BEGIN
/** /**
Returns the upload progress of the specified task. Returns the upload progress of the specified task.
@param task The session task. Must not be `nil`. @param uploadTask The session upload task. Must not be `nil`.
@return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable. @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable.
*/ */
- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task; - (nullable NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask;
/** /**
Returns the download progress of the specified task. Returns the download progress of the specified task.
@param task The session task. Must not be `nil`. @param downloadTask The session download task. Must not be `nil`.
@return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable. @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable.
*/ */
- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task; - (nullable NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask;
///----------------------------------------- ///-----------------------------------------
/// @name Setting Session Delegate Callbacks /// @name Setting Session Delegate Callbacks
...@@ -337,7 +339,7 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -337,7 +339,7 @@ NS_ASSUME_NONNULL_BEGIN
@param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. @param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge.
*/ */
- (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; - (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __nullable __autoreleasing * __nullable credential))block;
///-------------------------------------- ///--------------------------------------
/// @name Setting Task Delegate Callbacks /// @name Setting Task Delegate Callbacks
...@@ -355,14 +357,14 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -355,14 +357,14 @@ NS_ASSUME_NONNULL_BEGIN
@param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response. @param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response.
*/ */
- (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * _Nullable (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block; - (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block;
/** /**
Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`. Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`.
@param block A block object to be executed when a session task has received a request specific authentication challenge. The block returns the disposition of the authentication challenge, and takes four arguments: the session, the task, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. @param block A block object to be executed when a session task has received a request specific authentication challenge. The block returns the disposition of the authentication challenge, and takes four arguments: the session, the task, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge.
*/ */
- (void)setTaskDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; - (void)setTaskDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __nullable __autoreleasing * __nullable credential))block;
/** /**
Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
...@@ -376,7 +378,7 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -376,7 +378,7 @@ NS_ASSUME_NONNULL_BEGIN
@param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task. @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task.
*/ */
- (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block; - (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * __nullable error))block;
///------------------------------------------- ///-------------------------------------------
/// @name Setting Data Task Delegate Callbacks /// @name Setting Data Task Delegate Callbacks
...@@ -415,7 +417,7 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -415,7 +417,7 @@ NS_ASSUME_NONNULL_BEGIN
@param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session. @param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session.
*/ */
- (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block AF_API_UNAVAILABLE(macos); - (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block;
///----------------------------------------------- ///-----------------------------------------------
/// @name Setting Download Task Delegate Callbacks /// @name Setting Download Task Delegate Callbacks
...@@ -426,7 +428,7 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -426,7 +428,7 @@ NS_ASSUME_NONNULL_BEGIN
@param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error. @param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error.
*/ */
- (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block; - (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * __nullable (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block;
/** /**
Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`. Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`.
...@@ -444,17 +446,33 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -444,17 +446,33 @@ NS_ASSUME_NONNULL_BEGIN
@end @end
#endif
///-------------------- ///--------------------
/// @name Notifications /// @name Notifications
///-------------------- ///--------------------
/** /**
Posted when a task begins executing.
@deprecated Use `AFNetworkingTaskDidResumeNotification` instead.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidStartNotification DEPRECATED_ATTRIBUTE;
/**
Posted when a task resumes. Posted when a task resumes.
*/ */
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification; FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification;
/** /**
Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task.
@deprecated Use `AFNetworkingTaskDidCompleteNotification` instead.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidFinishNotification DEPRECATED_ATTRIBUTE;
/**
Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task.
*/ */
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification; FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification;
...@@ -474,27 +492,62 @@ FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification; ...@@ -474,27 +492,62 @@ FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification;
FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification; FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification;
/** /**
The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task. The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if response data exists for the task.
@deprecated Use `AFNetworkingTaskDidCompleteResponseDataKey` instead.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidFinishResponseDataKey DEPRECATED_ATTRIBUTE;
/**
The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if response data exists for the task.
*/ */
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey; FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey;
/** /**
The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized. The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the response was serialized.
@deprecated Use `AFNetworkingTaskDidCompleteSerializedResponseKey` instead.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidFinishSerializedResponseKey DEPRECATED_ATTRIBUTE;
/**
The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the response was serialized.
*/ */
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey; FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey;
/** /**
The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer. The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the task has an associated response serializer.
@deprecated Use `AFNetworkingTaskDidCompleteResponseSerializerKey` instead.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidFinishResponseSerializerKey DEPRECATED_ATTRIBUTE;
/**
The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the task has an associated response serializer.
*/ */
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey; FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey;
/** /**
The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an the response data has been stored directly to disk. The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an the response data has been stored directly to disk.
@deprecated Use `AFNetworkingTaskDidCompleteAssetPathKey` instead.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidFinishAssetPathKey DEPRECATED_ATTRIBUTE;
/**
The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an the response data has been stored directly to disk.
*/ */
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey; FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey;
/** /**
Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists. Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an error exists.
@deprecated Use `AFNetworkingTaskDidCompleteErrorKey` instead.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidFinishErrorKey DEPRECATED_ATTRIBUTE;
/**
Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an error exists.
*/ */
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey; FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey;
......
// AFURLSessionManager.m // AFURLSessionManager.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -22,11 +22,7 @@ ...@@ -22,11 +22,7 @@
#import "AFURLSessionManager.h" #import "AFURLSessionManager.h"
#import <objc/runtime.h> #import <objc/runtime.h>
#ifndef NSFoundationVersionNumber_iOS_8_0 #if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090)
#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug 1140.11
#else
#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug NSFoundationVersionNumber_iOS_8_0
#endif
static dispatch_queue_t url_session_manager_creation_queue() { static dispatch_queue_t url_session_manager_creation_queue() {
static dispatch_queue_t af_url_session_manager_creation_queue; static dispatch_queue_t af_url_session_manager_creation_queue;
...@@ -38,17 +34,6 @@ static dispatch_queue_t url_session_manager_creation_queue() { ...@@ -38,17 +34,6 @@ static dispatch_queue_t url_session_manager_creation_queue() {
return af_url_session_manager_creation_queue; return af_url_session_manager_creation_queue;
} }
static void url_session_manager_create_task_safely(dispatch_block_t block) {
if (NSFoundationVersionNumber < NSFoundationVersionNumber_With_Fixed_5871104061079552_bug) {
// Fix of bug
// Open Radar:http://openradar.appspot.com/radar?id=5871104061079552 (status: Fixed in iOS8)
// Issue about:https://github.com/AFNetworking/AFNetworking/issues/2093
dispatch_sync(url_session_manager_creation_queue(), block);
} else {
block();
}
}
static dispatch_queue_t url_session_manager_processing_queue() { static dispatch_queue_t url_session_manager_processing_queue() {
static dispatch_queue_t af_url_session_manager_processing_queue; static dispatch_queue_t af_url_session_manager_processing_queue;
static dispatch_once_t onceToken; static dispatch_once_t onceToken;
...@@ -75,16 +60,27 @@ NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networ ...@@ -75,16 +60,27 @@ NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networ
NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate"; NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate";
NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error"; NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error";
NSString * const AFNetworkingTaskDidStartNotification = @"com.alamofire.networking.task.resume"; // Deprecated
NSString * const AFNetworkingTaskDidFinishNotification = @"com.alamofire.networking.task.complete"; // Deprecated
NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse";
NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer";
NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata";
NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error"; NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error";
NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath";
NSString * const AFNetworkingTaskDidFinishSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; // Deprecated
NSString * const AFNetworkingTaskDidFinishResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; // Deprecated
NSString * const AFNetworkingTaskDidFinishResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; // Deprecated
NSString * const AFNetworkingTaskDidFinishErrorKey = @"com.alamofire.networking.task.complete.error"; // Deprecated
NSString * const AFNetworkingTaskDidFinishAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; // Deprecated
static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock"; static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock";
static NSUInteger const AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask = 3; static NSUInteger const AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask = 3;
static void * AFTaskStateChangedContext = &AFTaskStateChangedContext;
typedef void (^AFURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error); typedef void (^AFURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error);
typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential);
...@@ -104,95 +100,53 @@ typedef NSCachedURLResponse * (^AFURLSessionDataTaskWillCacheResponseBlock)(NSUR ...@@ -104,95 +100,53 @@ typedef NSCachedURLResponse * (^AFURLSessionDataTaskWillCacheResponseBlock)(NSUR
typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location); typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location);
typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite); typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite);
typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes); typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes);
typedef void (^AFURLSessionTaskProgressBlock)(NSProgress *);
typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error);
typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id __nullable responseObject, NSError *error);
#pragma mark - #pragma mark -
@interface AFURLSessionManagerTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate> @interface AFURLSessionManagerTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
- (instancetype)initWithTask:(NSURLSessionTask *)task;
@property (nonatomic, weak) AFURLSessionManager *manager; @property (nonatomic, weak) AFURLSessionManager *manager;
@property (nonatomic, strong) NSMutableData *mutableData; @property (nonatomic, strong) NSMutableData *mutableData;
@property (nonatomic, strong) NSProgress *uploadProgress; @property (nonatomic, strong) NSProgress *progress;
@property (nonatomic, strong) NSProgress *downloadProgress;
@property (nonatomic, copy) NSURL *downloadFileURL; @property (nonatomic, copy) NSURL *downloadFileURL;
@property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; @property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading;
@property (nonatomic, copy) AFURLSessionTaskProgressBlock uploadProgressBlock;
@property (nonatomic, copy) AFURLSessionTaskProgressBlock downloadProgressBlock;
@property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler; @property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler;
@end @end
@implementation AFURLSessionManagerTaskDelegate @implementation AFURLSessionManagerTaskDelegate
- (instancetype)initWithTask:(NSURLSessionTask *)task { - (instancetype)init {
self = [super init]; self = [super init];
if (!self) { if (!self) {
return nil; return nil;
} }
_mutableData = [NSMutableData data];
_uploadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil];
_downloadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil];
__weak __typeof__(task) weakTask = task;
for (NSProgress *progress in @[ _uploadProgress, _downloadProgress ])
{
progress.totalUnitCount = NSURLSessionTransferSizeUnknown;
progress.cancellable = YES;
progress.cancellationHandler = ^{
[weakTask cancel];
};
progress.pausable = YES;
progress.pausingHandler = ^{
[weakTask suspend];
};
#if AF_CAN_USE_AT_AVAILABLE
if (@available(iOS 9, macOS 10.11, *))
#else
if ([progress respondsToSelector:@selector(setResumingHandler:)])
#endif
{
progress.resumingHandler = ^{
[weakTask resume];
};
}
[progress addObserver:self
forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
options:NSKeyValueObservingOptionNew
context:NULL];
}
return self;
}
- (void)dealloc { self.mutableData = [NSMutableData data];
[self.downloadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))];
[self.uploadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))];
}
#pragma mark - NSProgress Tracking self.progress = [NSProgress progressWithTotalUnitCount:0];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context { return self;
if ([object isEqual:self.downloadProgress]) {
if (self.downloadProgressBlock) {
self.downloadProgressBlock(object);
}
}
else if ([object isEqual:self.uploadProgress]) {
if (self.uploadProgressBlock) {
self.uploadProgressBlock(object);
}
}
} }
#pragma mark - NSURLSessionTaskDelegate #pragma mark - NSURLSessionTaskDelegate
- (void)URLSession:(__unused NSURLSession *)session - (void)URLSession:(__unused NSURLSession *)session
task:(__unused NSURLSessionTask *)task
didSendBodyData:(__unused int64_t)bytesSent
totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
self.progress.totalUnitCount = totalBytesExpectedToSend;
self.progress.completedUnitCount = totalBytesSent;
}
- (void)URLSession:(__unused NSURLSession *)session
task:(NSURLSessionTask *)task task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error didCompleteWithError:(NSError *)error
{ {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
__strong AFURLSessionManager *manager = self.manager; __strong AFURLSessionManager *manager = self.manager;
__block id responseObject = nil; __block id responseObject = nil;
...@@ -254,66 +208,57 @@ didCompleteWithError:(NSError *)error ...@@ -254,66 +208,57 @@ didCompleteWithError:(NSError *)error
}); });
}); });
} }
#pragma clang diagnostic pop
} }
#pragma mark - NSURLSessionDataDelegate #pragma mark - NSURLSessionDataTaskDelegate
- (void)URLSession:(__unused NSURLSession *)session - (void)URLSession:(__unused NSURLSession *)session
dataTask:(__unused NSURLSessionDataTask *)dataTask dataTask:(__unused NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data didReceiveData:(NSData *)data
{ {
self.downloadProgress.totalUnitCount = dataTask.countOfBytesExpectedToReceive;
self.downloadProgress.completedUnitCount = dataTask.countOfBytesReceived;
[self.mutableData appendData:data]; [self.mutableData appendData:data];
} }
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task #pragma mark - NSURLSessionDownloadTaskDelegate
didSendBodyData:(int64_t)bytesSent
totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend;
self.uploadProgress.completedUnitCount = task.countOfBytesSent;
}
#pragma mark - NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
self.downloadProgress.totalUnitCount = totalBytesExpectedToWrite;
self.downloadProgress.completedUnitCount = totalBytesWritten;
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
self.downloadProgress.totalUnitCount = expectedTotalBytes;
self.downloadProgress.completedUnitCount = fileOffset;
}
- (void)URLSession:(NSURLSession *)session - (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location didFinishDownloadingToURL:(NSURL *)location
{ {
NSError *fileManagerError = nil;
self.downloadFileURL = nil; self.downloadFileURL = nil;
if (self.downloadTaskDidFinishDownloading) { if (self.downloadTaskDidFinishDownloading) {
self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
if (self.downloadFileURL) { if (self.downloadFileURL) {
NSError *fileManagerError = nil; [[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError];
if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError]) { if (fileManagerError) {
[[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo]; [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo];
} }
} }
} }
} }
- (void)URLSession:(__unused NSURLSession *)session
downloadTask:(__unused NSURLSessionDownloadTask *)downloadTask
didWriteData:(__unused int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
self.progress.totalUnitCount = totalBytesExpectedToWrite;
self.progress.completedUnitCount = totalBytesWritten;
}
- (void)URLSession:(__unused NSURLSession *)session
downloadTask:(__unused NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes {
self.progress.totalUnitCount = expectedTotalBytes;
self.progress.completedUnitCount = fileOffset;
}
@end @end
#pragma mark - #pragma mark -
...@@ -454,7 +399,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi ...@@ -454,7 +399,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
@property (readwrite, nonatomic, strong) NSLock *lock; @property (readwrite, nonatomic, strong) NSLock *lock;
@property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid; @property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid;
@property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge; @property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge;
@property (readwrite, nonatomic, copy) AFURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession AF_API_UNAVAILABLE(macos); @property (readwrite, nonatomic, copy) AFURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession;
@property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection; @property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection;
@property (readwrite, nonatomic, copy) AFURLSessionTaskDidReceiveAuthenticationChallengeBlock taskDidReceiveAuthenticationChallenge; @property (readwrite, nonatomic, copy) AFURLSessionTaskDidReceiveAuthenticationChallengeBlock taskDidReceiveAuthenticationChallenge;
@property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream; @property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream;
...@@ -507,7 +452,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi ...@@ -507,7 +452,7 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
[self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
for (NSURLSessionDataTask *task in dataTasks) { for (NSURLSessionDataTask *task in dataTasks) {
[self addDelegateForDataTask:task uploadProgress:nil downloadProgress:nil completionHandler:nil]; [self addDelegateForDataTask:task completionHandler:nil];
} }
for (NSURLSessionUploadTask *uploadTask in uploadTasks) { for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
...@@ -519,6 +464,9 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi ...@@ -519,6 +464,9 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
} }
}]; }];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:nil];
return self; return self;
} }
...@@ -575,47 +523,64 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi ...@@ -575,47 +523,64 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
[self.lock lock]; [self.lock lock];
self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate; self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate;
[self addNotificationObserverForTask:task];
[self.lock unlock]; [self.lock unlock];
} }
- (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask - (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask
uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock completionHandler:(AFURLSessionTaskCompletionHandler)completionHandler
downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{ {
AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:dataTask]; AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
delegate.manager = self; delegate.manager = self;
delegate.completionHandler = completionHandler; delegate.completionHandler = completionHandler;
dataTask.taskDescription = self.taskDescriptionForSessionTasks; dataTask.taskDescription = self.taskDescriptionForSessionTasks;
[self setDelegate:delegate forTask:dataTask]; [self setDelegate:delegate forTask:dataTask];
delegate.uploadProgressBlock = uploadProgressBlock;
delegate.downloadProgressBlock = downloadProgressBlock;
} }
- (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask - (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask
progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock progress:(NSProgress * __autoreleasing *)progress
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler completionHandler:(AFURLSessionTaskCompletionHandler)completionHandler
{ {
AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:uploadTask]; AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
delegate.manager = self; delegate.manager = self;
delegate.completionHandler = completionHandler; delegate.completionHandler = completionHandler;
int64_t totalUnitCount = uploadTask.countOfBytesExpectedToSend;
if(totalUnitCount == NSURLSessionTransferSizeUnknown) {
NSString *contentLength = [uploadTask.originalRequest valueForHTTPHeaderField:@"Content-Length"];
if(contentLength) {
totalUnitCount = (int64_t)[contentLength longLongValue];
}
}
if (delegate.progress) {
delegate.progress.totalUnitCount = totalUnitCount;
} else {
delegate.progress = [NSProgress progressWithTotalUnitCount:totalUnitCount];
}
delegate.progress.pausingHandler = ^{
[uploadTask suspend];
};
delegate.progress.cancellationHandler = ^{
[uploadTask cancel];
};
if (progress) {
*progress = delegate.progress;
}
uploadTask.taskDescription = self.taskDescriptionForSessionTasks; uploadTask.taskDescription = self.taskDescriptionForSessionTasks;
[self setDelegate:delegate forTask:uploadTask]; [self setDelegate:delegate forTask:uploadTask];
delegate.uploadProgressBlock = uploadProgressBlock;
} }
- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask - (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask
progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock progress:(NSProgress * __autoreleasing *)progress
destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{ {
AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:downloadTask]; AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
delegate.manager = self; delegate.manager = self;
delegate.completionHandler = completionHandler; delegate.completionHandler = completionHandler;
...@@ -625,22 +590,29 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi ...@@ -625,22 +590,29 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
}; };
} }
if (progress) {
*progress = delegate.progress;
}
downloadTask.taskDescription = self.taskDescriptionForSessionTasks; downloadTask.taskDescription = self.taskDescriptionForSessionTasks;
[self setDelegate:delegate forTask:downloadTask]; [self setDelegate:delegate forTask:downloadTask];
delegate.downloadProgressBlock = downloadProgressBlock;
} }
- (void)removeDelegateForTask:(NSURLSessionTask *)task { - (void)removeDelegateForTask:(NSURLSessionTask *)task {
NSParameterAssert(task); NSParameterAssert(task);
[self.lock lock]; [self.lock lock];
[self removeNotificationObserverForTask:task];
[self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)]; [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)];
[self.lock unlock]; [self.lock unlock];
} }
- (void)removeAllDelegates {
[self.lock lock];
[self.mutableTaskDelegatesKeyedByTaskIdentifier removeAllObjects];
[self.lock unlock];
}
#pragma mark - #pragma mark -
- (NSArray *)tasksForKeyPath:(NSString *)keyPath { - (NSArray *)tasksForKeyPath:(NSString *)keyPath {
...@@ -684,11 +656,13 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi ...@@ -684,11 +656,13 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
#pragma mark - #pragma mark -
- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks { - (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks {
if (cancelPendingTasks) { dispatch_async(dispatch_get_main_queue(), ^{
[self.session invalidateAndCancel]; if (cancelPendingTasks) {
} else { [self.session invalidateAndCancel];
[self.session finishTasksAndInvalidate]; } else {
} [self.session finishTasksAndInvalidate];
}
});
} }
#pragma mark - #pragma mark -
...@@ -700,35 +674,16 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi ...@@ -700,35 +674,16 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
} }
#pragma mark - #pragma mark -
- (void)addNotificationObserverForTask:(NSURLSessionTask *)task {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:task];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:task];
}
- (void)removeNotificationObserverForTask:(NSURLSessionTask *)task {
[[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidSuspendNotification object:task];
[[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidResumeNotification object:task];
}
#pragma mark -
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler completionHandler:(AFURLSessionTaskCompletionHandler)completionHandler
{ {
return [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:completionHandler];
}
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock
downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler {
__block NSURLSessionDataTask *dataTask = nil; __block NSURLSessionDataTask *dataTask = nil;
url_session_manager_create_task_safely(^{ dispatch_sync(url_session_manager_creation_queue(), ^{
dataTask = [self.session dataTaskWithRequest:request]; dataTask = [self.session dataTaskWithRequest:request];
}); });
[self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler]; [self addDelegateForDataTask:dataTask completionHandler:completionHandler];
return dataTask; return dataTask;
} }
...@@ -737,55 +692,50 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi ...@@ -737,55 +692,50 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromFile:(NSURL *)fileURL fromFile:(NSURL *)fileURL
progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock progress:(NSProgress * __autoreleasing *)progress
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler completionHandler:(AFURLSessionTaskCompletionHandler)completionHandler
{ {
__block NSURLSessionUploadTask *uploadTask = nil; __block NSURLSessionUploadTask *uploadTask = nil;
url_session_manager_create_task_safely(^{ dispatch_sync(url_session_manager_creation_queue(), ^{
uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL];
// uploadTask may be nil on iOS7 because uploadTaskWithRequest:fromFile: may return nil despite being documented as nonnull (https://devforums.apple.com/message/926113#926113)
if (!uploadTask && self.attemptsToRecreateUploadTasksForBackgroundSessions && self.session.configuration.identifier) {
for (NSUInteger attempts = 0; !uploadTask && attempts < AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask; attempts++) {
uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL];
}
}
}); });
if (uploadTask) { if (!uploadTask && self.attemptsToRecreateUploadTasksForBackgroundSessions && self.session.configuration.identifier) {
[self addDelegateForUploadTask:uploadTask for (NSUInteger attempts = 0; !uploadTask && attempts < AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask; attempts++) {
progress:uploadProgressBlock uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL];
completionHandler:completionHandler]; }
} }
[self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler];
return uploadTask; return uploadTask;
} }
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromData:(NSData *)bodyData fromData:(NSData *)bodyData
progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock progress:(NSProgress * __autoreleasing *)progress
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler completionHandler:(AFURLSessionTaskCompletionHandler)completionHandler
{ {
__block NSURLSessionUploadTask *uploadTask = nil; __block NSURLSessionUploadTask *uploadTask = nil;
url_session_manager_create_task_safely(^{ dispatch_sync(url_session_manager_creation_queue(), ^{
uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData]; uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData];
}); });
[self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler];
return uploadTask; return uploadTask;
} }
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request - (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock progress:(NSProgress * __autoreleasing *)progress
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler completionHandler:(AFURLSessionTaskCompletionHandler)completionHandler
{ {
__block NSURLSessionUploadTask *uploadTask = nil; __block NSURLSessionUploadTask *uploadTask = nil;
url_session_manager_create_task_safely(^{ dispatch_sync(url_session_manager_creation_queue(), ^{
uploadTask = [self.session uploadTaskWithStreamedRequest:request]; uploadTask = [self.session uploadTaskWithStreamedRequest:request];
}); });
[self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler];
return uploadTask; return uploadTask;
} }
...@@ -793,42 +743,43 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi ...@@ -793,42 +743,43 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
#pragma mark - #pragma mark -
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock progress:(NSProgress * __autoreleasing *)progress
destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{ {
__block NSURLSessionDownloadTask *downloadTask = nil; __block NSURLSessionDownloadTask *downloadTask = nil;
url_session_manager_create_task_safely(^{ dispatch_sync(url_session_manager_creation_queue(), ^{
downloadTask = [self.session downloadTaskWithRequest:request]; downloadTask = [self.session downloadTaskWithRequest:request];
}); });
[self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler]; [self addDelegateForDownloadTask:downloadTask progress:progress destination:destination completionHandler:completionHandler];
return downloadTask; return downloadTask;
} }
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock progress:(NSProgress * __autoreleasing *)progress
destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{ {
__block NSURLSessionDownloadTask *downloadTask = nil; __block NSURLSessionDownloadTask *downloadTask = nil;
url_session_manager_create_task_safely(^{ dispatch_sync(url_session_manager_creation_queue(), ^{
downloadTask = [self.session downloadTaskWithResumeData:resumeData]; downloadTask = [self.session downloadTaskWithResumeData:resumeData];
}); });
[self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler]; [self addDelegateForDownloadTask:downloadTask progress:progress destination:destination completionHandler:completionHandler];
return downloadTask; return downloadTask;
} }
#pragma mark - #pragma mark -
- (NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task {
return [[self delegateForTask:task] uploadProgress]; - (NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask {
return [[self delegateForTask:uploadTask] progress];
} }
- (NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task { - (NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask {
return [[self delegateForTask:task] downloadProgress]; return [[self delegateForTask:downloadTask] progress];
} }
#pragma mark - #pragma mark -
...@@ -841,11 +792,9 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi ...@@ -841,11 +792,9 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
self.sessionDidReceiveAuthenticationChallenge = block; self.sessionDidReceiveAuthenticationChallenge = block;
} }
#if !TARGET_OS_OSX
- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block { - (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block {
self.didFinishEventsForBackgroundURLSession = block; self.didFinishEventsForBackgroundURLSession = block;
} }
#endif
#pragma mark - #pragma mark -
...@@ -914,12 +863,9 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi ...@@ -914,12 +863,9 @@ static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofi
return self.dataTaskDidReceiveResponse != nil; return self.dataTaskDidReceiveResponse != nil;
} else if (selector == @selector(URLSession:dataTask:willCacheResponse:completionHandler:)) { } else if (selector == @selector(URLSession:dataTask:willCacheResponse:completionHandler:)) {
return self.dataTaskWillCacheResponse != nil; return self.dataTaskWillCacheResponse != nil;
} } else if (selector == @selector(URLSessionDidFinishEventsForBackgroundURLSession:)) {
#if !TARGET_OS_OSX
else if (selector == @selector(URLSessionDidFinishEventsForBackgroundURLSession:)) {
return self.didFinishEventsForBackgroundURLSession != nil; return self.didFinishEventsForBackgroundURLSession != nil;
} }
#endif
return [[self class] instancesRespondToSelector:selector]; return [[self class] instancesRespondToSelector:selector];
} }
...@@ -933,6 +879,7 @@ didBecomeInvalidWithError:(NSError *)error ...@@ -933,6 +879,7 @@ didBecomeInvalidWithError:(NSError *)error
self.sessionDidBecomeInvalid(session, error); self.sessionDidBecomeInvalid(session, error);
} }
[self removeAllDelegates];
[[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session]; [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session];
} }
...@@ -1045,12 +992,9 @@ totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend ...@@ -1045,12 +992,9 @@ totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
totalUnitCount = (int64_t) [contentLength longLongValue]; totalUnitCount = (int64_t) [contentLength longLongValue];
} }
} }
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
[delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalUnitCount];
if (delegate) {
[delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalBytesExpectedToSend];
}
if (self.taskDidSendBodyData) { if (self.taskDidSendBodyData) {
self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalUnitCount); self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalUnitCount);
...@@ -1073,6 +1017,7 @@ didCompleteWithError:(NSError *)error ...@@ -1073,6 +1017,7 @@ didCompleteWithError:(NSError *)error
if (self.taskDidComplete) { if (self.taskDidComplete) {
self.taskDidComplete(session, task, error); self.taskDidComplete(session, task, error);
} }
} }
#pragma mark - NSURLSessionDataDelegate #pragma mark - NSURLSessionDataDelegate
...@@ -1112,7 +1057,6 @@ didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask ...@@ -1112,7 +1057,6 @@ didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
dataTask:(NSURLSessionDataTask *)dataTask dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data didReceiveData:(NSData *)data
{ {
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask];
[delegate URLSession:session dataTask:dataTask didReceiveData:data]; [delegate URLSession:session dataTask:dataTask didReceiveData:data];
...@@ -1137,7 +1081,6 @@ didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask ...@@ -1137,7 +1081,6 @@ didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
} }
} }
#if !TARGET_OS_OSX
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session { - (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
if (self.didFinishEventsForBackgroundURLSession) { if (self.didFinishEventsForBackgroundURLSession) {
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
...@@ -1145,7 +1088,6 @@ didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask ...@@ -1145,7 +1088,6 @@ didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
}); });
} }
} }
#endif
#pragma mark - NSURLSessionDownloadDelegate #pragma mark - NSURLSessionDownloadDelegate
...@@ -1159,8 +1101,8 @@ didFinishDownloadingToURL:(NSURL *)location ...@@ -1159,8 +1101,8 @@ didFinishDownloadingToURL:(NSURL *)location
if (fileURL) { if (fileURL) {
delegate.downloadFileURL = fileURL; delegate.downloadFileURL = fileURL;
NSError *error = nil; NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error];
if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error]) { if (error) {
[[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo]; [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo];
} }
...@@ -1179,12 +1121,8 @@ didFinishDownloadingToURL:(NSURL *)location ...@@ -1179,12 +1121,8 @@ didFinishDownloadingToURL:(NSURL *)location
totalBytesWritten:(int64_t)totalBytesWritten totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{ {
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
[delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
if (delegate) {
[delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
}
if (self.downloadTaskDidWriteData) { if (self.downloadTaskDidWriteData) {
self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
...@@ -1196,12 +1134,8 @@ totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite ...@@ -1196,12 +1134,8 @@ totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
didResumeAtOffset:(int64_t)fileOffset didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes expectedTotalBytes:(int64_t)expectedTotalBytes
{ {
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
[delegate URLSession:session downloadTask:downloadTask didResumeAtOffset:fileOffset expectedTotalBytes:expectedTotalBytes];
if (delegate) {
[delegate URLSession:session downloadTask:downloadTask didResumeAtOffset:fileOffset expectedTotalBytes:expectedTotalBytes];
}
if (self.downloadTaskDidResume) { if (self.downloadTaskDidResume) {
self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes); self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes);
...@@ -1214,7 +1148,7 @@ expectedTotalBytes:(int64_t)expectedTotalBytes ...@@ -1214,7 +1148,7 @@ expectedTotalBytes:(int64_t)expectedTotalBytes
return YES; return YES;
} }
- (instancetype)initWithCoder:(NSCoder *)decoder { - (id)initWithCoder:(NSCoder *)decoder {
NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
self = [self initWithSessionConfiguration:configuration]; self = [self initWithSessionConfiguration:configuration];
...@@ -1231,8 +1165,10 @@ expectedTotalBytes:(int64_t)expectedTotalBytes ...@@ -1231,8 +1165,10 @@ expectedTotalBytes:(int64_t)expectedTotalBytes
#pragma mark - NSCopying #pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone { - (id)copyWithZone:(NSZone *)zone {
return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration]; return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration];
} }
@end @end
#endif
Copyright (c) 2011-2016 Alamofire Software Foundation (http://alamofire.org/) Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
......
...@@ -3,13 +3,8 @@ ...@@ -3,13 +3,8 @@
</p> </p>
[![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.svg)](https://travis-ci.org/AFNetworking/AFNetworking) [![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.svg)](https://travis-ci.org/AFNetworking/AFNetworking)
[![codecov.io](https://codecov.io/github/AFNetworking/AFNetworking/coverage.svg?branch=master)](https://codecov.io/github/AFNetworking/AFNetworking?branch=master)
[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/AFNetworking.svg)](https://img.shields.io/cocoapods/v/AFNetworking.svg)
[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![Platform](https://img.shields.io/cocoapods/p/AFNetworking.svg?style=flat)](http://cocoadocs.org/docsets/AFNetworking)
[![Twitter](https://img.shields.io/badge/twitter-@AFNetworking-blue.svg?style=flat)](http://twitter.com/AFNetworking)
AFNetworking is a delightful networking library for iOS, macOS, watchOS, and tvOS. It's built on top of the [Foundation URL Loading System](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html), extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of the [Foundation URL Loading System](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html), extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.
Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac. Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac.
...@@ -20,7 +15,7 @@ Choose AFNetworking for your next project, or migrate over your existing project ...@@ -20,7 +15,7 @@ Choose AFNetworking for your next project, or migrate over your existing project
- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/archive/master.zip) and try out the included Mac and iPhone example apps - [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/archive/master.zip) and try out the included Mac and iPhone example apps
- Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles on the Wiki](https://github.com/AFNetworking/AFNetworking/wiki) - Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles on the Wiki](https://github.com/AFNetworking/AFNetworking/wiki)
- Check out the [documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at all of the APIs available in AFNetworking - Check out the [documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at all of the APIs available in AFNetworking
- Read the [AFNetworking 3.0 Migration Guide](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-3.0-Migration-Guide) for an overview of the architectural changes from 2.0. - Read the [AFNetworking 2.0 Migration Guide](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-2.0-Migration-Guide) for an overview of the architectural changes from 1.0.
## Communication ## Communication
...@@ -30,74 +25,39 @@ Choose AFNetworking for your next project, or migrate over your existing project ...@@ -30,74 +25,39 @@ Choose AFNetworking for your next project, or migrate over your existing project
- If you **have a feature request**, open an issue. - If you **have a feature request**, open an issue.
- If you **want to contribute**, submit a pull request. - If you **want to contribute**, submit a pull request.
## Installation ### Installation with CocoaPods
AFNetworking supports multiple methods for installing the library in a project.
## Installation with CocoaPods [CocoaPods](https://cocoapods.org/) is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries like AFNetworking in your projects. See the ["Getting Started" guide for more information](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking).
[CocoaPods](http://cocoapods.org) is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries like AFNetworking in your projects. See the ["Getting Started" guide for more information](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking). You can install it with the following command:
```bash
$ gem install cocoapods
```
> CocoaPods 0.39.0+ is required to build AFNetworking 3.0.0+.
#### Podfile #### Podfile
To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your `Podfile`:
```ruby ```ruby
source 'https://github.com/CocoaPods/Specs.git' platform :ios, '7.0'
platform :ios, '8.0' pod "AFNetworking", "~> 2.0"
target 'TargetName' do
pod 'AFNetworking', '~> 3.0'
end
``` ```
Then, run the following command:
```bash
$ pod install
```
### Installation with Carthage
[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.
You can install Carthage with [Homebrew](http://brew.sh/) using the following command:
```bash
$ brew update
$ brew install carthage
```
To integrate AFNetworking into your Xcode project using Carthage, specify it in your `Cartfile`:
```ogdl
github "AFNetworking/AFNetworking" ~> 3.0
```
Run `carthage` to build the framework and drag the built `AFNetworking.framework` into your Xcode project.
## Requirements ## Requirements
| AFNetworking Version | Minimum iOS Target | Minimum macOS Target | Minimum watchOS Target | Minimum tvOS Target | Notes | | AFNetworking Version | Minimum iOS Target | Minimum OS X Target | watchOS Target | Notes |
|:--------------------:|:---------------------------:|:----------------------------:|:----------------------------:|:----------------------------:|:-------------------------------------------------------------------------:| |:--------------------:|:---------------------------:|:----------------------------:|:----------------------------:|:-------------------------------------------------------------------------:|
| 3.x | iOS 7 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Xcode 7+ is required. `NSURLConnectionOperation` support has been removed. | | 2.6+ | iOS 7 | OS X 10.9 | watchOS 2.0 | |
| 2.6 -> 2.6.3 | iOS 7 | OS X 10.9 | watchOS 2.0 | n/a | Xcode 7+ is required. | | 2.0.0 -> 2.5.4 | iOS 6 | OS X 10.8 | N/A | Xcode 5 is required. `NSURLSession` subspec requires iOS 7 or OS X 10.9. |
| 2.0 -> 2.5.4 | iOS 6 | OS X 10.8 | n/a | n/a | Xcode 5+ is required. `NSURLSession` subspec requires iOS 7 or OS X 10.9. | | [1.x](https://github.com/AFNetworking/AFNetworking/tree/1.x) | iOS 5 | Mac OS X 10.7 | N/A | |
| 1.x | iOS 5 | Mac OS X 10.7 | n/a | n/a | | [0.10.x](https://github.com/AFNetworking/AFNetworking/tree/0.10.x) | iOS 4 | Mac OS X 10.6 | N/A | |
| 0.10.x | iOS 4 | Mac OS X 10.6 | n/a | n/a |
(macOS projects must support [64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)). (OS X projects must support [64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)).
> Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs. > Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs.
## Architecture ## Architecture
### NSURLSession ### NSURLConnection
- `AFURLConnectionOperation`
- `AFHTTPRequestOperation`
- `AFHTTPRequestOperationManager`
### NSURLSession _(iOS 7 / Mac OS X 10.9)_
- `AFURLSessionManager` - `AFURLSessionManager`
- `AFHTTPSessionManager` - `AFHTTPSessionManager`
...@@ -112,7 +72,7 @@ Run `carthage` to build the framework and drag the built `AFNetworking.framework ...@@ -112,7 +72,7 @@ Run `carthage` to build the framework and drag the built `AFNetworking.framework
- `AFHTTPResponseSerializer` - `AFHTTPResponseSerializer`
- `AFJSONResponseSerializer` - `AFJSONResponseSerializer`
- `AFXMLParserResponseSerializer` - `AFXMLParserResponseSerializer`
- `AFXMLDocumentResponseSerializer` _(macOS)_ - `AFXMLDocumentResponseSerializer` _(Mac OS X)_
- `AFPropertyListResponseSerializer` - `AFPropertyListResponseSerializer`
- `AFImageResponseSerializer` - `AFImageResponseSerializer`
- `AFCompoundResponseSerializer` - `AFCompoundResponseSerializer`
...@@ -124,6 +84,50 @@ Run `carthage` to build the framework and drag the built `AFNetworking.framework ...@@ -124,6 +84,50 @@ Run `carthage` to build the framework and drag the built `AFNetworking.framework
## Usage ## Usage
### HTTP Request Operation Manager
`AFHTTPRequestOperationManager` encapsulates the common patterns of communicating with a web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as request operation management.
#### `GET` Request
```objective-c
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
```
#### `POST` URL-Form-Encoded Request
```objective-c
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
```
#### `POST` Multi-Part Request
```objective-c
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<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:@"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
```
---
### AFURLSessionManager ### AFURLSessionManager
`AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`. `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
...@@ -174,25 +178,15 @@ NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFo ...@@ -174,25 +178,15 @@ NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFo
} error:nil]; } error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;
NSURLSessionUploadTask *uploadTask; NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
uploadTask = [manager if (error) {
uploadTaskWithStreamedRequest:request NSLog(@"Error: %@", error);
progress:^(NSProgress * _Nonnull uploadProgress) { } else {
// This is not called back on the main queue. NSLog(@"%@ %@", response, responseObject);
// You are responsible for dispatching to the main queue for UI updates }
dispatch_async(dispatch_get_main_queue(), ^{ }];
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[uploadTask resume]; [uploadTask resume];
``` ```
...@@ -203,7 +197,7 @@ uploadTask = [manager ...@@ -203,7 +197,7 @@ uploadTask = [manager
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"]; NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL]; NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
...@@ -238,7 +232,7 @@ NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]}; ...@@ -238,7 +232,7 @@ NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
#### URL Form Parameter Encoding #### URL Form Parameter Encoding
```objective-c ```objective-c
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
``` ```
POST http://example.com/ POST http://example.com/
...@@ -249,7 +243,7 @@ NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]}; ...@@ -249,7 +243,7 @@ NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
#### JSON Parameter Encoding #### JSON Parameter Encoding
```objective-c ```objective-c
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
``` ```
POST http://example.com/ POST http://example.com/
...@@ -282,6 +276,29 @@ See also [WWDC 2012 session 706, "Networking Best Practices."](https://developer ...@@ -282,6 +276,29 @@ See also [WWDC 2012 session 706, "Networking Best Practices."](https://developer
[[AFNetworkReachabilityManager sharedManager] startMonitoring]; [[AFNetworkReachabilityManager sharedManager] startMonitoring];
``` ```
#### HTTP Manager Reachability
```objective-c
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
NSOperationQueue *operationQueue = manager.operationQueue;
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN:
case AFNetworkReachabilityStatusReachableViaWiFi:
[operationQueue setSuspended:NO];
break;
case AFNetworkReachabilityStatusNotReachable:
default:
[operationQueue setSuspended:YES];
break;
}
}];
[manager.reachabilityManager startMonitoring];
```
--- ---
### Security Policy ### Security Policy
...@@ -293,25 +310,73 @@ Adding pinned SSL certificates to your app helps prevent man-in-the-middle attac ...@@ -293,25 +310,73 @@ Adding pinned SSL certificates to your app helps prevent man-in-the-middle attac
#### Allowing Invalid SSL Certificates #### Allowing Invalid SSL Certificates
```objective-c ```objective-c
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production
``` ```
--- ---
### AFHTTPRequestOperation
`AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
Although `AFHTTPRequestOperationManager` is usually the best way to go about making requests, `AFHTTPRequestOperation` can be used by itself.
#### `GET` with `AFHTTPRequestOperation`
```objective-c
NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[[NSOperationQueue mainQueue] addOperation:op];
```
#### Batch of Operations
```objective-c
NSMutableArray *mutableOperations = [NSMutableArray array];
for (NSURL *fileURL in filesToUpload) {
NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[mutableOperations addObject:operation];
}
NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);
} completionBlock:^(NSArray *operations) {
NSLog(@"All operations in batch complete");
}];
[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];
```
## Unit Tests ## Unit Tests
AFNetworking includes a suite of unit tests within the Tests subdirectory. These tests can be run simply be executed the test action on the platform framework you would like to test. AFNetworking includes a suite of unit tests within the Tests subdirectory. In order to run the unit tests, you must install the testing dependencies via [CocoaPods](https://cocoapods.org/):
$ cd Tests
$ pod install
Once testing dependencies are installed, you can execute the test suite via the 'iOS Tests' and 'OS X Tests' schemes within Xcode.
## Credits ## Credits
AFNetworking is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). AFNetworking is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org).
AFNetworking was originally created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla). AFNetworking was originally created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](https://en.wikipedia.org/wiki/Gowalla).
AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/). AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/).
And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors). And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/graphs/contributors).
### Security Disclosure ### Security Disclosure
...@@ -319,4 +384,4 @@ If you believe you have identified a security vulnerability with AFNetworking, y ...@@ -319,4 +384,4 @@ If you believe you have identified a security vulnerability with AFNetworking, y
## License ## License
AFNetworking is released under the MIT license. See [LICENSE](https://github.com/AFNetworking/AFNetworking/blob/master/LICENSE) for details. AFNetworking is released under the MIT license. See LICENSE for details.
// AFAutoPurgingImageCache.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// 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 <TargetConditionals.h>
#import <Foundation/Foundation.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
The `AFImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously.
*/
@protocol AFImageCache <NSObject>
/**
Adds the image to the cache with the given identifier.
@param image The image to cache.
@param identifier The unique identifier for the image in the cache.
*/
- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier;
/**
Removes the image from the cache matching the given identifier.
@param identifier The unique identifier for the image in the cache.
@return A BOOL indicating whether or not the image was removed from the cache.
*/
- (BOOL)removeImageWithIdentifier:(NSString *)identifier;
/**
Removes all images from the cache.
@return A BOOL indicating whether or not all images were removed from the cache.
*/
- (BOOL)removeAllImages;
/**
Returns the image in the cache associated with the given identifier.
@param identifier The unique identifier for the image in the cache.
@return An image for the matching identifier, or nil.
*/
- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier;
@end
/**
The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and fetching images from a cache given an `NSURLRequest` and additional identifier.
*/
@protocol AFImageRequestCache <AFImageCache>
/**
Asks if the image should be cached using an identifier created from the request and additional identifier.
@param image The image to be cached.
@param request The unique URL request identifing the image asset.
@param identifier The additional identifier to apply to the URL request to identify the image.
@return A BOOL indicating whether or not the image should be added to the cache. YES will cache, NO will prevent caching.
*/
- (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
/**
Adds the image to the cache using an identifier created from the request and additional identifier.
@param image The image to cache.
@param request The unique URL request identifing the image asset.
@param identifier The additional identifier to apply to the URL request to identify the image.
*/
- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
/**
Removes the image from the cache using an identifier created from the request and additional identifier.
@param request The unique URL request identifing the image asset.
@param identifier The additional identifier to apply to the URL request to identify the image.
@return A BOOL indicating whether or not all images were removed from the cache.
*/
- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
/**
Returns the image from the cache associated with an identifier created from the request and additional identifier.
@param request The unique URL request identifing the image asset.
@param identifier The additional identifier to apply to the URL request to identify the image.
@return An image for the matching request and identifier, or nil.
*/
- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
@end
/**
The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated.
*/
@interface AFAutoPurgingImageCache : NSObject <AFImageRequestCache>
/**
The total memory capacity of the cache in bytes.
*/
@property (nonatomic, assign) UInt64 memoryCapacity;
/**
The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit.
*/
@property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge;
/**
The current total memory usage in bytes of all images stored within the cache.
*/
@property (nonatomic, assign, readonly) UInt64 memoryUsage;
/**
Initialies the `AutoPurgingImageCache` instance with default values for memory capacity and preferred memory usage after purge limit. `memoryCapcity` defaults to `100 MB`. `preferredMemoryUsageAfterPurge` defaults to `60 MB`.
@return The new `AutoPurgingImageCache` instance.
*/
- (instancetype)init;
/**
Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage
after purge limit.
@param memoryCapacity The total memory capacity of the cache in bytes.
@param preferredMemoryCapacity The preferred memory usage after purge in bytes.
@return The new `AutoPurgingImageCache` instance.
*/
- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity;
@end
NS_ASSUME_NONNULL_END
#endif
// AFAutoPurgingImageCache.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// 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 <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import "AFAutoPurgingImageCache.h"
@interface AFCachedImage : NSObject
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) NSString *identifier;
@property (nonatomic, assign) UInt64 totalBytes;
@property (nonatomic, strong) NSDate *lastAccessDate;
@property (nonatomic, assign) UInt64 currentMemoryUsage;
@end
@implementation AFCachedImage
-(instancetype)initWithImage:(UIImage *)image identifier:(NSString *)identifier {
if (self = [self init]) {
self.image = image;
self.identifier = identifier;
CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale);
CGFloat bytesPerPixel = 4.0;
CGFloat bytesPerSize = imageSize.width * imageSize.height;
self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerSize;
self.lastAccessDate = [NSDate date];
}
return self;
}
- (UIImage*)accessImage {
self.lastAccessDate = [NSDate date];
return self.image;
}
- (NSString *)description {
NSString *descriptionString = [NSString stringWithFormat:@"Idenfitier: %@ lastAccessDate: %@ ", self.identifier, self.lastAccessDate];
return descriptionString;
}
@end
@interface AFAutoPurgingImageCache ()
@property (nonatomic, strong) NSMutableDictionary <NSString* , AFCachedImage*> *cachedImages;
@property (nonatomic, assign) UInt64 currentMemoryUsage;
@property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
@end
@implementation AFAutoPurgingImageCache
- (instancetype)init {
return [self initWithMemoryCapacity:100 * 1024 * 1024 preferredMemoryCapacity:60 * 1024 * 1024];
}
- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity {
if (self = [super init]) {
self.memoryCapacity = memoryCapacity;
self.preferredMemoryUsageAfterPurge = preferredMemoryCapacity;
self.cachedImages = [[NSMutableDictionary alloc] init];
NSString *queueName = [NSString stringWithFormat:@"com.alamofire.autopurgingimagecache-%@", [[NSUUID UUID] UUIDString]];
self.synchronizationQueue = dispatch_queue_create([queueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT);
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(removeAllImages)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (UInt64)memoryUsage {
__block UInt64 result = 0;
dispatch_sync(self.synchronizationQueue, ^{
result = self.currentMemoryUsage;
});
return result;
}
- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier {
dispatch_barrier_async(self.synchronizationQueue, ^{
AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier];
AFCachedImage *previousCachedImage = self.cachedImages[identifier];
if (previousCachedImage != nil) {
self.currentMemoryUsage -= previousCachedImage.totalBytes;
}
self.cachedImages[identifier] = cacheImage;
self.currentMemoryUsage += cacheImage.totalBytes;
});
dispatch_barrier_async(self.synchronizationQueue, ^{
if (self.currentMemoryUsage > self.memoryCapacity) {
UInt64 bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge;
NSMutableArray <AFCachedImage*> *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate"
ascending:YES];
[sortedImages sortUsingDescriptors:@[sortDescriptor]];
UInt64 bytesPurged = 0;
for (AFCachedImage *cachedImage in sortedImages) {
[self.cachedImages removeObjectForKey:cachedImage.identifier];
bytesPurged += cachedImage.totalBytes;
if (bytesPurged >= bytesToPurge) {
break ;
}
}
self.currentMemoryUsage -= bytesPurged;
}
});
}
- (BOOL)removeImageWithIdentifier:(NSString *)identifier {
__block BOOL removed = NO;
dispatch_barrier_sync(self.synchronizationQueue, ^{
AFCachedImage *cachedImage = self.cachedImages[identifier];
if (cachedImage != nil) {
[self.cachedImages removeObjectForKey:identifier];
self.currentMemoryUsage -= cachedImage.totalBytes;
removed = YES;
}
});
return removed;
}
- (BOOL)removeAllImages {
__block BOOL removed = NO;
dispatch_barrier_sync(self.synchronizationQueue, ^{
if (self.cachedImages.count > 0) {
[self.cachedImages removeAllObjects];
self.currentMemoryUsage = 0;
removed = YES;
}
});
return removed;
}
- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier {
__block UIImage *image = nil;
dispatch_sync(self.synchronizationQueue, ^{
AFCachedImage *cachedImage = self.cachedImages[identifier];
image = [cachedImage accessImage];
});
return image;
}
- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
[self addImage:image withIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
}
- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
return [self removeImageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
}
- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
return [self imageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
}
- (NSString *)imageCacheKeyFromURLRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)additionalIdentifier {
NSString *key = request.URL.absoluteString;
if (additionalIdentifier != nil) {
key = [key stringByAppendingString:additionalIdentifier];
}
return key;
}
- (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier {
return YES;
}
@end
#endif
// AFImageDownloader.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// 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 <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import <Foundation/Foundation.h>
#import "AFAutoPurgingImageCache.h"
#import "AFHTTPSessionManager.h"
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, AFImageDownloadPrioritization) {
AFImageDownloadPrioritizationFIFO,
AFImageDownloadPrioritizationLIFO
};
/**
The `AFImageDownloadReceipt` is an object vended by the `AFImageDownloader` when starting a data task. It can be used to cancel active tasks running on the `AFImageDownloader` session. As a general rule, image data tasks should be cancelled using the `AFImageDownloadReceipt` instead of calling `cancel` directly on the `task` itself. The `AFImageDownloader` is optimized to handle duplicate task scenarios as well as pending versus active downloads.
*/
@interface AFImageDownloadReceipt : NSObject
/**
The data task created by the `AFImageDownloader`.
*/
@property (nonatomic, strong) NSURLSessionDataTask *task;
/**
The unique identifier for the success and failure blocks when duplicate requests are made.
*/
@property (nonatomic, strong) NSUUID *receiptID;
@end
/** The `AFImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying `NSURLCache` as well as the in-memory image cache. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation.
*/
@interface AFImageDownloader : NSObject
/**
The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default.
*/
@property (nonatomic, strong, nullable) id <AFImageRequestCache> imageCache;
/**
The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads.
*/
@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
/**
Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default.
*/
@property (nonatomic, assign) AFImageDownloadPrioritization downloadPrioritizaton;
/**
The shared default instance of `AFImageDownloader` initialized with default values.
*/
+ (instancetype)defaultInstance;
/**
Creates a default `NSURLCache` with common usage parameter values.
@returns The default `NSURLCache` instance.
*/
+ (NSURLCache *)defaultURLCache;
/**
The default `NSURLSessionConfiguration` with common usage parameter values.
*/
+ (NSURLSessionConfiguration *)defaultURLSessionConfiguration;
/**
Default initializer
@return An instance of `AFImageDownloader` initialized with default values.
*/
- (instancetype)init;
/**
Initializer with specific `URLSessionConfiguration`
@param configuration The `NSURLSessionConfiguration` to be be used
@return An instance of `AFImageDownloader` initialized with default values and custom `NSURLSessionConfiguration`
*/
- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration;
/**
Initializes the `AFImageDownloader` instance with the given session manager, download prioritization, maximum active download count and image cache.
@param sessionManager The session manager to use to download images.
@param downloadPrioritization The download prioritization of the download queue.
@param maximumActiveDownloads The maximum number of active downloads allowed at any given time. Recommend `4`.
@param imageCache The image cache used to store all downloaded images in.
@return The new `AFImageDownloader` instance.
*/
- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager
downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization
maximumActiveDownloads:(NSInteger)maximumActiveDownloads
imageCache:(nullable id <AFImageRequestCache>)imageCache;
/**
Creates a data task using the `sessionManager` instance for the specified URL request.
If the same data task is already in the queue or currently being downloaded, the success and failure blocks are
appended to the already existing task. Once the task completes, all success or failure blocks attached to the
task are executed in the order they were added.
@param request The URL request.
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
@return The image download receipt for the data task if available. `nil` if the image is stored in the cache.
cache and the URL request cache policy allows the cache to be used.
*/
- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
/**
Creates a data task using the `sessionManager` instance for the specified URL request.
If the same data task is already in the queue or currently being downloaded, the success and failure blocks are
appended to the already existing task. Once the task completes, all success or failure blocks attached to the
task are executed in the order they were added.
@param request The URL request.
@param receiptID The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request.
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
@return The image download receipt for the data task if available. `nil` if the image is stored in the cache.
cache and the URL request cache policy allows the cache to be used.
*/
- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
withReceiptID:(NSUUID *)receiptID
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
/**
Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary.
If the data task is pending in the queue, it will be cancelled if no other success and failure blocks are registered with the data task. If the data task is currently executing or is already completed, the success and failure blocks are removed and will not be called when the task finishes.
@param imageDownloadReceipt The image download receipt to cancel.
*/
- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt;
@end
#endif
NS_ASSUME_NONNULL_END
// AFImageDownloader.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// 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 <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import "AFImageDownloader.h"
#import "AFHTTPSessionManager.h"
@interface AFImageDownloaderResponseHandler : NSObject
@property (nonatomic, strong) NSUUID *uuid;
@property (nonatomic, copy) void (^successBlock)(NSURLRequest*, NSHTTPURLResponse*, UIImage*);
@property (nonatomic, copy) void (^failureBlock)(NSURLRequest*, NSHTTPURLResponse*, NSError*);
@end
@implementation AFImageDownloaderResponseHandler
- (instancetype)initWithUUID:(NSUUID *)uuid
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure {
if (self = [self init]) {
self.uuid = uuid;
self.successBlock = success;
self.failureBlock = failure;
}
return self;
}
- (NSString *)description {
return [NSString stringWithFormat: @"<AFImageDownloaderResponseHandler>UUID: %@", [self.uuid UUIDString]];
}
@end
@interface AFImageDownloaderMergedTask : NSObject
@property (nonatomic, strong) NSString *URLIdentifier;
@property (nonatomic, strong) NSUUID *identifier;
@property (nonatomic, strong) NSURLSessionDataTask *task;
@property (nonatomic, strong) NSMutableArray <AFImageDownloaderResponseHandler*> *responseHandlers;
@end
@implementation AFImageDownloaderMergedTask
- (instancetype)initWithURLIdentifier:(NSString *)URLIdentifier identifier:(NSUUID *)identifier task:(NSURLSessionDataTask *)task {
if (self = [self init]) {
self.URLIdentifier = URLIdentifier;
self.task = task;
self.identifier = identifier;
self.responseHandlers = [[NSMutableArray alloc] init];
}
return self;
}
- (void)addResponseHandler:(AFImageDownloaderResponseHandler*)handler {
[self.responseHandlers addObject:handler];
}
- (void)removeResponseHandler:(AFImageDownloaderResponseHandler*)handler {
[self.responseHandlers removeObject:handler];
}
@end
@implementation AFImageDownloadReceipt
- (instancetype)initWithReceiptID:(NSUUID *)receiptID task:(NSURLSessionDataTask *)task {
if (self = [self init]) {
self.receiptID = receiptID;
self.task = task;
}
return self;
}
@end
@interface AFImageDownloader ()
@property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
@property (nonatomic, strong) dispatch_queue_t responseQueue;
@property (nonatomic, assign) NSInteger maximumActiveDownloads;
@property (nonatomic, assign) NSInteger activeRequestCount;
@property (nonatomic, strong) NSMutableArray *queuedMergedTasks;
@property (nonatomic, strong) NSMutableDictionary *mergedTasks;
@end
@implementation AFImageDownloader
+ (NSURLCache *)defaultURLCache {
// It's been discovered that a crash will occur on certain versions
// of iOS if you customize the cache.
//
// More info can be found here: https://devforums.apple.com/message/1102182#1102182
//
// When iOS 7 support is dropped, this should be modified to use
// NSProcessInfo methods instead.
if ([[[UIDevice currentDevice] systemVersion] compare:@"8.2" options:NSNumericSearch] == NSOrderedAscending) {
return [NSURLCache sharedURLCache];
}
return [[NSURLCache alloc] initWithMemoryCapacity:20 * 1024 * 1024
diskCapacity:150 * 1024 * 1024
diskPath:@"com.alamofire.imagedownloader"];
}
+ (NSURLSessionConfiguration *)defaultURLSessionConfiguration {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//TODO set the default HTTP headers
configuration.HTTPShouldSetCookies = YES;
configuration.HTTPShouldUsePipelining = NO;
configuration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
configuration.allowsCellularAccess = YES;
configuration.timeoutIntervalForRequest = 60.0;
configuration.URLCache = [AFImageDownloader defaultURLCache];
return configuration;
}
- (instancetype)init {
NSURLSessionConfiguration *defaultConfiguration = [self.class defaultURLSessionConfiguration];
return [self initWithSessionConfiguration:defaultConfiguration];
}
- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
sessionManager.responseSerializer = [AFImageResponseSerializer serializer];
return [self initWithSessionManager:sessionManager
downloadPrioritization:AFImageDownloadPrioritizationFIFO
maximumActiveDownloads:4
imageCache:[[AFAutoPurgingImageCache alloc] init]];
}
- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager
downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization
maximumActiveDownloads:(NSInteger)maximumActiveDownloads
imageCache:(id <AFImageRequestCache>)imageCache {
if (self = [super init]) {
self.sessionManager = sessionManager;
self.downloadPrioritizaton = downloadPrioritization;
self.maximumActiveDownloads = maximumActiveDownloads;
self.imageCache = imageCache;
self.queuedMergedTasks = [[NSMutableArray alloc] init];
self.mergedTasks = [[NSMutableDictionary alloc] init];
self.activeRequestCount = 0;
NSString *name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.synchronizationqueue-%@", [[NSUUID UUID] UUIDString]];
self.synchronizationQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL);
name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.responsequeue-%@", [[NSUUID UUID] UUIDString]];
self.responseQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT);
}
return self;
}
+ (instancetype)defaultInstance {
static AFImageDownloader *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
success:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, UIImage * _Nonnull))success
failure:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, NSError * _Nonnull))failure {
return [self downloadImageForURLRequest:request withReceiptID:[NSUUID UUID] success:success failure:failure];
}
- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
withReceiptID:(nonnull NSUUID *)receiptID
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure {
__block NSURLSessionDataTask *task = nil;
dispatch_sync(self.synchronizationQueue, ^{
NSString *URLIdentifier = request.URL.absoluteString;
if (URLIdentifier == nil) {
if (failure) {
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil];
dispatch_async(dispatch_get_main_queue(), ^{
failure(request, nil, error);
});
}
return;
}
// 1) Append the success and failure blocks to a pre-existing request if it already exists
AFImageDownloaderMergedTask *existingMergedTask = self.mergedTasks[URLIdentifier];
if (existingMergedTask != nil) {
AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID success:success failure:failure];
[existingMergedTask addResponseHandler:handler];
task = existingMergedTask.task;
return;
}
// 2) Attempt to load the image from the image cache if the cache policy allows it
switch (request.cachePolicy) {
case NSURLRequestUseProtocolCachePolicy:
case NSURLRequestReturnCacheDataElseLoad:
case NSURLRequestReturnCacheDataDontLoad: {
UIImage *cachedImage = [self.imageCache imageforRequest:request withAdditionalIdentifier:nil];
if (cachedImage != nil) {
if (success) {
dispatch_async(dispatch_get_main_queue(), ^{
success(request, nil, cachedImage);
});
}
return;
}
break;
}
default:
break;
}
// 3) Create the request and set up authentication, validation and response serialization
NSUUID *mergedTaskIdentifier = [NSUUID UUID];
NSURLSessionDataTask *createdTask;
__weak __typeof__(self) weakSelf = self;
createdTask = [self.sessionManager
dataTaskWithRequest:request
uploadProgress:nil
downloadProgress:nil
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
dispatch_async(self.responseQueue, ^{
__strong __typeof__(weakSelf) strongSelf = weakSelf;
AFImageDownloaderMergedTask *mergedTask = strongSelf.mergedTasks[URLIdentifier];
if ([mergedTask.identifier isEqual:mergedTaskIdentifier]) {
mergedTask = [strongSelf safelyRemoveMergedTaskWithURLIdentifier:URLIdentifier];
if (error) {
for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {
if (handler.failureBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
handler.failureBlock(request, (NSHTTPURLResponse*)response, error);
});
}
}
} else {
if ([strongSelf.imageCache shouldCacheImage:responseObject forRequest:request withAdditionalIdentifier:nil]) {
[strongSelf.imageCache addImage:responseObject forRequest:request withAdditionalIdentifier:nil];
}
for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {
if (handler.successBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
handler.successBlock(request, (NSHTTPURLResponse*)response, responseObject);
});
}
}
}
}
[strongSelf safelyDecrementActiveTaskCount];
[strongSelf safelyStartNextTaskIfNecessary];
});
}];
// 4) Store the response handler for use when the request completes
AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID
success:success
failure:failure];
AFImageDownloaderMergedTask *mergedTask = [[AFImageDownloaderMergedTask alloc]
initWithURLIdentifier:URLIdentifier
identifier:mergedTaskIdentifier
task:createdTask];
[mergedTask addResponseHandler:handler];
self.mergedTasks[URLIdentifier] = mergedTask;
// 5) Either start the request or enqueue it depending on the current active request count
if ([self isActiveRequestCountBelowMaximumLimit]) {
[self startMergedTask:mergedTask];
} else {
[self enqueueMergedTask:mergedTask];
}
task = mergedTask.task;
});
if (task) {
return [[AFImageDownloadReceipt alloc] initWithReceiptID:receiptID task:task];
} else {
return nil;
}
}
- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt {
dispatch_sync(self.synchronizationQueue, ^{
NSString *URLIdentifier = imageDownloadReceipt.task.originalRequest.URL.absoluteString;
AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
NSUInteger index = [mergedTask.responseHandlers indexOfObjectPassingTest:^BOOL(AFImageDownloaderResponseHandler * _Nonnull handler, __unused NSUInteger idx, __unused BOOL * _Nonnull stop) {
return handler.uuid == imageDownloadReceipt.receiptID;
}];
if (index != NSNotFound) {
AFImageDownloaderResponseHandler *handler = mergedTask.responseHandlers[index];
[mergedTask removeResponseHandler:handler];
NSString *failureReason = [NSString stringWithFormat:@"ImageDownloader cancelled URL request: %@",imageDownloadReceipt.task.originalRequest.URL.absoluteString];
NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey:failureReason};
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
if (handler.failureBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
handler.failureBlock(imageDownloadReceipt.task.originalRequest, nil, error);
});
}
}
if (mergedTask.responseHandlers.count == 0 && mergedTask.task.state == NSURLSessionTaskStateSuspended) {
[mergedTask.task cancel];
[self removeMergedTaskWithURLIdentifier:URLIdentifier];
}
});
}
- (AFImageDownloaderMergedTask*)safelyRemoveMergedTaskWithURLIdentifier:(NSString *)URLIdentifier {
__block AFImageDownloaderMergedTask *mergedTask = nil;
dispatch_sync(self.synchronizationQueue, ^{
mergedTask = [self removeMergedTaskWithURLIdentifier:URLIdentifier];
});
return mergedTask;
}
//This method should only be called from safely within the synchronizationQueue
- (AFImageDownloaderMergedTask *)removeMergedTaskWithURLIdentifier:(NSString *)URLIdentifier {
AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
[self.mergedTasks removeObjectForKey:URLIdentifier];
return mergedTask;
}
- (void)safelyDecrementActiveTaskCount {
dispatch_sync(self.synchronizationQueue, ^{
if (self.activeRequestCount > 0) {
self.activeRequestCount -= 1;
}
});
}
- (void)safelyStartNextTaskIfNecessary {
dispatch_sync(self.synchronizationQueue, ^{
if ([self isActiveRequestCountBelowMaximumLimit]) {
while (self.queuedMergedTasks.count > 0) {
AFImageDownloaderMergedTask *mergedTask = [self dequeueMergedTask];
if (mergedTask.task.state == NSURLSessionTaskStateSuspended) {
[self startMergedTask:mergedTask];
break;
}
}
}
});
}
- (void)startMergedTask:(AFImageDownloaderMergedTask *)mergedTask {
[mergedTask.task resume];
++self.activeRequestCount;
}
- (void)enqueueMergedTask:(AFImageDownloaderMergedTask *)mergedTask {
switch (self.downloadPrioritizaton) {
case AFImageDownloadPrioritizationFIFO:
[self.queuedMergedTasks addObject:mergedTask];
break;
case AFImageDownloadPrioritizationLIFO:
[self.queuedMergedTasks insertObject:mergedTask atIndex:0];
break;
}
}
- (AFImageDownloaderMergedTask *)dequeueMergedTask {
AFImageDownloaderMergedTask *mergedTask = nil;
mergedTask = [self.queuedMergedTasks firstObject];
[self.queuedMergedTasks removeObject:mergedTask];
return mergedTask;
}
- (BOOL)isActiveRequestCountBelowMaximumLimit {
return self.activeRequestCount < self.maximumActiveDownloads;
}
@end
#endif
// AFNetworkActivityIndicatorManager.h // AFNetworkActivityIndicatorManager.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -21,16 +21,16 @@ ...@@ -21,16 +21,16 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <TargetConditionals.h> #import <Availability.h>
#if TARGET_OS_IOS #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
/** /**
`AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a session task has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero. `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a network request operation has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero.
You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code: You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code:
...@@ -52,25 +52,9 @@ NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropri ...@@ -52,25 +52,9 @@ NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropri
@property (nonatomic, assign, getter = isEnabled) BOOL enabled; @property (nonatomic, assign, getter = isEnabled) BOOL enabled;
/** /**
A Boolean value indicating whether the network activity indicator manager is currently active. A Boolean value indicating whether the network activity indicator is currently displayed in the status bar.
*/
@property (readonly, nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
/**
A time interval indicating the minimum duration of networking activity that should occur before the activity indicator is displayed. The default value 1 second. If the network activity indicator should be displayed immediately when network activity occurs, this value should be set to 0 seconds.
Apple's HIG describes the following:
> Display the network activity indicator to provide feedback when your app accesses the network for more than a couple of seconds. If the operation finishes sooner than that, you don’t have to show the network activity indicator, because the indicator is likely to disappear before users notice its presence.
*/
@property (nonatomic, assign) NSTimeInterval activationDelay;
/**
A time interval indicating the duration of time of no networking activity required before the activity indicator is disabled. This allows for continuous display of the network activity indicator across multiple requests. The default value is 0.17 seconds.
*/ */
@property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible;
@property (nonatomic, assign) NSTimeInterval completionDelay;
/** /**
Returns the shared network activity indicator manager object for the system. Returns the shared network activity indicator manager object for the system.
...@@ -89,13 +73,6 @@ NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropri ...@@ -89,13 +73,6 @@ NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropri
*/ */
- (void)decrementActivityCount; - (void)decrementActivityCount;
/**
Set the a custom method to be executed when the network activity indicator manager should be hidden/shown. By default, this is null, and the UIApplication Network Activity Indicator will be managed automatically. If this block is set, it is the responsiblity of the caller to manager the network activity indicator going forward.
@param block A block to be executed when the network activity indicator status changes.
*/
- (void)setNetworkingActivityActionWithBlock:(nullable void (^)(BOOL networkActivityIndicatorVisible))block;
@end @end
NS_ASSUME_NONNULL_END NS_ASSUME_NONNULL_END
......
// AFNetworkActivityIndicatorManager.m // AFNetworkActivityIndicatorManager.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -21,42 +21,41 @@ ...@@ -21,42 +21,41 @@
#import "AFNetworkActivityIndicatorManager.h" #import "AFNetworkActivityIndicatorManager.h"
#if TARGET_OS_IOS #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED)
#import "AFURLSessionManager.h"
#import "AFHTTPRequestOperation.h"
typedef NS_ENUM(NSInteger, AFNetworkActivityManagerState) { #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
AFNetworkActivityManagerStateNotActive, #import "AFURLSessionManager.h"
AFNetworkActivityManagerStateDelayingStart, #endif
AFNetworkActivityManagerStateActive,
AFNetworkActivityManagerStateDelayingEnd
};
static NSTimeInterval const kDefaultAFNetworkActivityManagerActivationDelay = 1.0; static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17;
static NSTimeInterval const kDefaultAFNetworkActivityManagerCompletionDelay = 0.17;
static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) { static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) {
if ([[notification object] isKindOfClass:[AFURLConnectionOperation class]]) {
return [(AFURLConnectionOperation *)[notification object] request];
}
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
if ([[notification object] respondsToSelector:@selector(originalRequest)]) { if ([[notification object] respondsToSelector:@selector(originalRequest)]) {
return [(NSURLSessionTask *)[notification object] originalRequest]; return [(NSURLSessionTask *)[notification object] originalRequest];
} else {
return nil;
} }
} #endif
typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisible); return nil;
}
@interface AFNetworkActivityIndicatorManager () @interface AFNetworkActivityIndicatorManager ()
@property (readwrite, nonatomic, assign) NSInteger activityCount; @property (readwrite, nonatomic, assign) NSInteger activityCount;
@property (readwrite, nonatomic, strong) NSTimer *activationDelayTimer; @property (readwrite, nonatomic, strong) NSTimer *activityIndicatorVisibilityTimer;
@property (readwrite, nonatomic, strong) NSTimer *completionDelayTimer; @property (readonly, nonatomic, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
@property (readonly, nonatomic, getter = isNetworkActivityOccurring) BOOL networkActivityOccurring;
@property (nonatomic, copy) AFNetworkActivityActionBlock networkActivityActionBlock; - (void)updateNetworkActivityIndicatorVisibility;
@property (nonatomic, assign) AFNetworkActivityManagerState currentState; - (void)updateNetworkActivityIndicatorVisibilityDelayed;
@property (nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
- (void)updateCurrentStateForNetworkActivityChange;
@end @end
@implementation AFNetworkActivityIndicatorManager @implementation AFNetworkActivityIndicatorManager
@dynamic networkActivityIndicatorVisible;
+ (instancetype)sharedManager { + (instancetype)sharedManager {
static AFNetworkActivityIndicatorManager *_sharedManager = nil; static AFNetworkActivityIndicatorManager *_sharedManager = nil;
...@@ -68,17 +67,24 @@ typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisibl ...@@ -68,17 +67,24 @@ typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisibl
return _sharedManager; return _sharedManager;
} }
- (instancetype)init { + (NSSet *)keyPathsForValuesAffectingIsNetworkActivityIndicatorVisible {
return [NSSet setWithObject:@"activityCount"];
}
- (id)init {
self = [super init]; self = [super init];
if (!self) { if (!self) {
return nil; return nil;
} }
self.currentState = AFNetworkActivityManagerStateNotActive;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingOperationDidStartNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingOperationDidFinishNotification object:nil];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil];
self.activationDelay = kDefaultAFNetworkActivityManagerActivationDelay; #endif
self.completionDelay = kDefaultAFNetworkActivityManagerCompletionDelay;
return self; return self;
} }
...@@ -86,40 +92,28 @@ typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisibl ...@@ -86,40 +92,28 @@ typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisibl
- (void)dealloc { - (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self]; [[NSNotificationCenter defaultCenter] removeObserver:self];
[_activationDelayTimer invalidate]; [_activityIndicatorVisibilityTimer invalidate];
[_completionDelayTimer invalidate];
} }
- (void)setEnabled:(BOOL)enabled { - (void)updateNetworkActivityIndicatorVisibilityDelayed {
_enabled = enabled; if (self.enabled) {
if (enabled == NO) { // Delay hiding of activity indicator for a short interval, to avoid flickering
[self setCurrentState:AFNetworkActivityManagerStateNotActive]; if (![self isNetworkActivityIndicatorVisible]) {
[self.activityIndicatorVisibilityTimer invalidate];
self.activityIndicatorVisibilityTimer = [NSTimer timerWithTimeInterval:kAFNetworkActivityIndicatorInvisibilityDelay target:self selector:@selector(updateNetworkActivityIndicatorVisibility) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:self.activityIndicatorVisibilityTimer forMode:NSRunLoopCommonModes];
} else {
[self performSelectorOnMainThread:@selector(updateNetworkActivityIndicatorVisibility) withObject:nil waitUntilDone:NO modes:@[NSRunLoopCommonModes]];
}
} }
} }
- (void)setNetworkingActivityActionWithBlock:(void (^)(BOOL networkActivityIndicatorVisible))block { - (BOOL)isNetworkActivityIndicatorVisible {
self.networkActivityActionBlock = block; return self.activityCount > 0;
}
- (BOOL)isNetworkActivityOccurring {
@synchronized(self) {
return self.activityCount > 0;
}
} }
- (void)setNetworkActivityIndicatorVisible:(BOOL)networkActivityIndicatorVisible { - (void)updateNetworkActivityIndicatorVisibility {
if (_networkActivityIndicatorVisible != networkActivityIndicatorVisible) { [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]];
[self willChangeValueForKey:@"networkActivityIndicatorVisible"];
@synchronized(self) {
_networkActivityIndicatorVisible = networkActivityIndicatorVisible;
}
[self didChangeValueForKey:@"networkActivityIndicatorVisible"];
if (self.networkActivityActionBlock) {
self.networkActivityActionBlock(networkActivityIndicatorVisible);
} else {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:networkActivityIndicatorVisible];
}
}
} }
- (void)setActivityCount:(NSInteger)activityCount { - (void)setActivityCount:(NSInteger)activityCount {
...@@ -128,7 +122,7 @@ typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisibl ...@@ -128,7 +122,7 @@ typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisibl
} }
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
[self updateCurrentStateForNetworkActivityChange]; [self updateNetworkActivityIndicatorVisibilityDelayed];
}); });
} }
...@@ -140,19 +134,22 @@ typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisibl ...@@ -140,19 +134,22 @@ typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisibl
[self didChangeValueForKey:@"activityCount"]; [self didChangeValueForKey:@"activityCount"];
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
[self updateCurrentStateForNetworkActivityChange]; [self updateNetworkActivityIndicatorVisibilityDelayed];
}); });
} }
- (void)decrementActivityCount { - (void)decrementActivityCount {
[self willChangeValueForKey:@"activityCount"]; [self willChangeValueForKey:@"activityCount"];
@synchronized(self) { @synchronized(self) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
_activityCount = MAX(_activityCount - 1, 0); _activityCount = MAX(_activityCount - 1, 0);
#pragma clang diagnostic pop
} }
[self didChangeValueForKey:@"activityCount"]; [self didChangeValueForKey:@"activityCount"];
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
[self updateCurrentStateForNetworkActivityChange]; [self updateNetworkActivityIndicatorVisibilityDelayed];
}); });
} }
...@@ -168,92 +165,6 @@ typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisibl ...@@ -168,92 +165,6 @@ typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisibl
} }
} }
#pragma mark - Internal State Management
- (void)setCurrentState:(AFNetworkActivityManagerState)currentState {
@synchronized(self) {
if (_currentState != currentState) {
[self willChangeValueForKey:@"currentState"];
_currentState = currentState;
switch (currentState) {
case AFNetworkActivityManagerStateNotActive:
[self cancelActivationDelayTimer];
[self cancelCompletionDelayTimer];
[self setNetworkActivityIndicatorVisible:NO];
break;
case AFNetworkActivityManagerStateDelayingStart:
[self startActivationDelayTimer];
break;
case AFNetworkActivityManagerStateActive:
[self cancelCompletionDelayTimer];
[self setNetworkActivityIndicatorVisible:YES];
break;
case AFNetworkActivityManagerStateDelayingEnd:
[self startCompletionDelayTimer];
break;
}
[self didChangeValueForKey:@"currentState"];
}
}
}
- (void)updateCurrentStateForNetworkActivityChange {
if (self.enabled) {
switch (self.currentState) {
case AFNetworkActivityManagerStateNotActive:
if (self.isNetworkActivityOccurring) {
[self setCurrentState:AFNetworkActivityManagerStateDelayingStart];
}
break;
case AFNetworkActivityManagerStateDelayingStart:
//No op. Let the delay timer finish out.
break;
case AFNetworkActivityManagerStateActive:
if (!self.isNetworkActivityOccurring) {
[self setCurrentState:AFNetworkActivityManagerStateDelayingEnd];
}
break;
case AFNetworkActivityManagerStateDelayingEnd:
if (self.isNetworkActivityOccurring) {
[self setCurrentState:AFNetworkActivityManagerStateActive];
}
break;
}
}
}
- (void)startActivationDelayTimer {
self.activationDelayTimer = [NSTimer
timerWithTimeInterval:self.activationDelay target:self selector:@selector(activationDelayTimerFired) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:self.activationDelayTimer forMode:NSRunLoopCommonModes];
}
- (void)activationDelayTimerFired {
if (self.networkActivityOccurring) {
[self setCurrentState:AFNetworkActivityManagerStateActive];
} else {
[self setCurrentState:AFNetworkActivityManagerStateNotActive];
}
}
- (void)startCompletionDelayTimer {
[self.completionDelayTimer invalidate];
self.completionDelayTimer = [NSTimer timerWithTimeInterval:self.completionDelay target:self selector:@selector(completionDelayTimerFired) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:self.completionDelayTimer forMode:NSRunLoopCommonModes];
}
- (void)completionDelayTimerFired {
[self setCurrentState:AFNetworkActivityManagerStateNotActive];
}
- (void)cancelActivationDelayTimer {
[self.activationDelayTimer invalidate];
}
- (void)cancelCompletionDelayTimer {
[self.completionDelayTimer invalidate];
}
@end @end
#endif #endif
// UIActivityIndicatorView+AFNetworking.h // UIActivityIndicatorView+AFNetworking.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -21,14 +21,16 @@ ...@@ -21,14 +21,16 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <TargetConditionals.h> #import <Availability.h>
#if TARGET_OS_IOS || TARGET_OS_TV #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
@class AFURLConnectionOperation;
/** /**
This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a session task. This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a request operation or session task.
*/ */
@interface UIActivityIndicatorView (AFNetworking) @interface UIActivityIndicatorView (AFNetworking)
...@@ -41,7 +43,20 @@ ...@@ -41,7 +43,20 @@
@param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled.
*/ */
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
- (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task; - (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task;
#endif
///---------------------------------------
/// @name Animating for Request Operations
///---------------------------------------
/**
Binds the animating state to the execution state of the specified operation.
@param operation The operation. If `nil`, automatic updating from any previously specified operation will be disabled.
*/
- (void)setAnimatingWithStateOfOperation:(nullable AFURLConnectionOperation *)operation;
@end @end
......
// UIActivityIndicatorView+AFNetworking.m // UIActivityIndicatorView+AFNetworking.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -22,15 +22,22 @@ ...@@ -22,15 +22,22 @@
#import "UIActivityIndicatorView+AFNetworking.h" #import "UIActivityIndicatorView+AFNetworking.h"
#import <objc/runtime.h> #import <objc/runtime.h>
#if TARGET_OS_IOS || TARGET_OS_TV #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import "AFHTTPRequestOperation.h"
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
#import "AFURLSessionManager.h" #import "AFURLSessionManager.h"
#endif
@interface AFActivityIndicatorViewNotificationObserver : NSObject @interface AFActivityIndicatorViewNotificationObserver : NSObject
@property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView; @property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView;
- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView; - (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView;
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task; - (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task;
#endif
- (void)setAnimatingWithStateOfOperation:(AFURLConnectionOperation *)operation;
@end @end
...@@ -45,9 +52,15 @@ ...@@ -45,9 +52,15 @@
return notificationObserver; return notificationObserver;
} }
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { - (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
[[self af_notificationObserver] setAnimatingWithStateOfTask:task]; [[self af_notificationObserver] setAnimatingWithStateOfTask:task];
} }
#endif
- (void)setAnimatingWithStateOfOperation:(AFURLConnectionOperation *)operation {
[[self af_notificationObserver] setAnimatingWithStateOfOperation:operation];
}
@end @end
...@@ -62,6 +75,7 @@ ...@@ -62,6 +75,7 @@
return self; return self;
} }
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { - (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
...@@ -71,12 +85,16 @@ ...@@ -71,12 +85,16 @@
if (task) { if (task) {
if (task.state != NSURLSessionTaskStateCompleted) { if (task.state != NSURLSessionTaskStateCompleted) {
UIActivityIndicatorView *activityIndicatorView = self.activityIndicatorView;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreceiver-is-weak"
#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak"
if (task.state == NSURLSessionTaskStateRunning) { if (task.state == NSURLSessionTaskStateRunning) {
[activityIndicatorView startAnimating]; [self.activityIndicatorView startAnimating];
} else { } else {
[activityIndicatorView stopAnimating]; [self.activityIndicatorView stopAnimating];
} }
#pragma clang diagnostic pop
[notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task]; [notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task];
[notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task]; [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task];
...@@ -84,18 +102,52 @@ ...@@ -84,18 +102,52 @@
} }
} }
} }
#endif
#pragma mark -
- (void)setAnimatingWithStateOfOperation:(AFURLConnectionOperation *)operation {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil];
if (operation) {
if (![operation isFinished]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreceiver-is-weak"
#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak"
if ([operation isExecuting]) {
[self.activityIndicatorView startAnimating];
} else {
[self.activityIndicatorView stopAnimating];
}
#pragma clang diagnostic pop
[notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingOperationDidStartNotification object:operation];
[notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingOperationDidFinishNotification object:operation];
}
}
}
#pragma mark - #pragma mark -
- (void)af_startAnimating { - (void)af_startAnimating {
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreceiver-is-weak"
[self.activityIndicatorView startAnimating]; [self.activityIndicatorView startAnimating];
#pragma clang diagnostic pop
}); });
} }
- (void)af_stopAnimating { - (void)af_stopAnimating {
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreceiver-is-weak"
[self.activityIndicatorView stopAnimating]; [self.activityIndicatorView stopAnimating];
#pragma clang diagnostic pop
}); });
} }
...@@ -104,9 +156,14 @@ ...@@ -104,9 +156,14 @@
- (void)dealloc { - (void)dealloc {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
#endif
[notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil];
} }
@end @end
......
// UIAlertView+AFNetworking.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 <Foundation/Foundation.h>
#import <Availability.h>
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@class AFURLConnectionOperation;
/**
This category adds methods to the UIKit framework's `UIAlertView` class. The methods in this category provide support for automatically showing an alert if a session task or request operation finishes with an error. Alert title and message are filled from the corresponding `localizedDescription` & `localizedRecoverySuggestion` or `localizedFailureReason` of the error.
*/
@interface UIAlertView (AFNetworking)
///-------------------------------------
/// @name Showing Alert for Session Task
///-------------------------------------
/**
Shows an alert view with the error of the specified session task, if any.
@param task The session task.
@param delegate The alert view delegate.
*/
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
+ (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task
delegate:(nullable id)delegate NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions.");
#endif
/**
Shows an alert view with the error of the specified session task, if any, with a custom cancel button title and other button titles.
@param task The session task.
@param delegate The alert view delegate.
@param cancelButtonTitle The title of the cancel button or nil if there is no cancel button. Using this argument is equivalent to setting the cancel button index to the value returned by invoking addButtonWithTitle: specifying this title.
@param otherButtonTitles The title of another button. Using this argument is equivalent to invoking addButtonWithTitle: with this title to add more buttons. Too many buttons can cause the alert view to scroll. For guidelines on the best ways to use an alert in an app, see "Temporary Views". Titles of additional buttons to add to the receiver, terminated with `nil`.
*/
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
+ (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task
delegate:(nullable id)delegate
cancelButtonTitle:(nullable NSString *)cancelButtonTitle
otherButtonTitles:(nullable NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions.");
#endif
///------------------------------------------
/// @name Showing Alert for Request Operation
///------------------------------------------
/**
Shows an alert view with the error of the specified request operation, if any.
@param operation The request operation.
@param delegate The alert view delegate.
*/
+ (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation
delegate:(nullable id)delegate NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions.");
/**
Shows an alert view with the error of the specified request operation, if any, with a custom cancel button title and other button titles.
@param operation The request operation.
@param delegate The alert view delegate.
@param cancelButtonTitle The title of the cancel button or nil if there is no cancel button. Using this argument is equivalent to setting the cancel button index to the value returned by invoking addButtonWithTitle: specifying this title.
@param otherButtonTitles The title of another button. Using this argument is equivalent to invoking addButtonWithTitle: with this title to add more buttons. Too many buttons can cause the alert view to scroll. For guidelines on the best ways to use an alert in an app, see "Temporary Views". Titles of additional buttons to add to the receiver, terminated with `nil`.
*/
+ (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation
delegate:(nullable id)delegate
cancelButtonTitle:(nullable NSString *)cancelButtonTitle
otherButtonTitles:(nullable NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions.");
@end
NS_ASSUME_NONNULL_END
#endif
// UIAlertView+AFNetworking.m
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 "UIAlertView+AFNetworking.h"
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import "AFURLConnectionOperation.h"
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
#import "AFURLSessionManager.h"
#endif
static void AFGetAlertViewTitleAndMessageFromError(NSError *error, NSString * __autoreleasing *title, NSString * __autoreleasing *message) {
if (error.localizedDescription && (error.localizedRecoverySuggestion || error.localizedFailureReason)) {
*title = error.localizedDescription;
if (error.localizedRecoverySuggestion) {
*message = error.localizedRecoverySuggestion;
} else {
*message = error.localizedFailureReason;
}
} else if (error.localizedDescription) {
*title = NSLocalizedStringFromTable(@"Error", @"AFNetworking", @"Fallback Error Description");
*message = error.localizedDescription;
} else {
*title = NSLocalizedStringFromTable(@"Error", @"AFNetworking", @"Fallback Error Description");
*message = [NSString stringWithFormat:NSLocalizedStringFromTable(@"%@ Error: %ld", @"AFNetworking", @"Fallback Error Failure Reason Format"), error.domain, (long)error.code];
}
}
@implementation UIAlertView (AFNetworking)
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
+ (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task
delegate:(id)delegate
{
[self showAlertViewForTaskWithErrorOnCompletion:task delegate:delegate cancelButtonTitle:NSLocalizedStringFromTable(@"Dismiss", @"AFNetworking", @"UIAlertView Cancel Button Title") otherButtonTitles:nil, nil];
}
+ (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task
delegate:(id)delegate
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION
{
NSMutableArray *mutableOtherTitles = [NSMutableArray array];
va_list otherButtonTitleList;
va_start(otherButtonTitleList, otherButtonTitles);
{
for (NSString *otherButtonTitle = otherButtonTitles; otherButtonTitle != nil; otherButtonTitle = va_arg(otherButtonTitleList, NSString *)) {
[mutableOtherTitles addObject:otherButtonTitle];
}
}
va_end(otherButtonTitleList);
__block __weak id<NSObject> observer = [[NSNotificationCenter defaultCenter] addObserverForName:AFNetworkingTaskDidCompleteNotification object:task queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) {
NSError *error = notification.userInfo[AFNetworkingTaskDidCompleteErrorKey];
if (error) {
NSString *title, *message;
AFGetAlertViewTitleAndMessageFromError(error, &title, &message);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil, nil];
for (NSString *otherButtonTitle in mutableOtherTitles) {
[alertView addButtonWithTitle:otherButtonTitle];
}
[alertView setTitle:title];
[alertView setMessage:message];
[alertView show];
}
[[NSNotificationCenter defaultCenter] removeObserver:observer];
}];
}
#endif
#pragma mark -
+ (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation
delegate:(id)delegate
{
[self showAlertViewForRequestOperationWithErrorOnCompletion:operation delegate:delegate cancelButtonTitle:NSLocalizedStringFromTable(@"Dismiss", @"AFNetworking", @"UIAlertView Cancel Button Title") otherButtonTitles:nil, nil];
}
+ (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation
delegate:(id)delegate
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION
{
NSMutableArray *mutableOtherTitles = [NSMutableArray array];
va_list otherButtonTitleList;
va_start(otherButtonTitleList, otherButtonTitles);
{
for (NSString *otherButtonTitle = otherButtonTitles; otherButtonTitle != nil; otherButtonTitle = va_arg(otherButtonTitleList, NSString *)) {
[mutableOtherTitles addObject:otherButtonTitle];
}
}
va_end(otherButtonTitleList);
__block __weak id<NSObject> observer = [[NSNotificationCenter defaultCenter] addObserverForName:AFNetworkingOperationDidFinishNotification object:operation queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) {
if (notification.object && [notification.object isKindOfClass:[AFURLConnectionOperation class]]) {
NSError *error = [(AFURLConnectionOperation *)notification.object error];
if (error) {
NSString *title, *message;
AFGetAlertViewTitleAndMessageFromError(error, &title, &message);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil, nil];
for (NSString *otherButtonTitle in mutableOtherTitles) {
[alertView addButtonWithTitle:otherButtonTitle];
}
[alertView setTitle:title];
[alertView setMessage:message];
[alertView show];
}
}
[[NSNotificationCenter defaultCenter] removeObserver:observer];
}];
}
@end
#endif
// UIButton+AFNetworking.h // UIButton+AFNetworking.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -21,15 +21,15 @@ ...@@ -21,15 +21,15 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <TargetConditionals.h> #import <Availability.h>
#if TARGET_OS_IOS || TARGET_OS_TV #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
@class AFImageDownloader; @protocol AFURLResponseSerialization, AFImageCache;
/** /**
This category adds methods to the UIKit framework's `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL. This category adds methods to the UIKit framework's `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL.
...@@ -38,21 +38,32 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -38,21 +38,32 @@ NS_ASSUME_NONNULL_BEGIN
*/ */
@interface UIButton (AFNetworking) @interface UIButton (AFNetworking)
///------------------------------------ ///----------------------------
/// @name Accessing the Image Downloader /// @name Accessing Image Cache
///------------------------------------ ///----------------------------
/**
The image cache used to improve image loading performance on scroll views. By default, `UIButton` will use the `sharedImageCache` of `UIImageView`.
*/
+ (id <AFImageCache>)sharedImageCache;
/** /**
Set the shared image downloader used to download images. Set the cache used for image loading.
@param imageDownloader The shared image downloader used to download images. @param imageCache The image cache.
*/ */
+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; + (void)setSharedImageCache:(__nullable id <AFImageCache>)imageCache;
///------------------------------------
/// @name Accessing Response Serializer
///------------------------------------
/** /**
The shared image downloader used to download images. The response serializer used to create an image representation from the server response and response data. By default, this is an instance of `AFImageResponseSerializer`.
@discussion Subclasses of `AFImageResponseSerializer` could be used to perform post-processing, such as color correction, face detection, or other effects. See https://github.com/AFNetworking/AFCoreImageSerializer
*/ */
+ (AFImageDownloader *)sharedImageDownloader; @property (nonatomic, strong) id <AFURLResponseSerialization> imageResponseSerializer;
///-------------------- ///--------------------
/// @name Setting Image /// @name Setting Image
...@@ -92,14 +103,14 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -92,14 +103,14 @@ NS_ASSUME_NONNULL_BEGIN
@param state The control state. @param state The control state.
@param urlRequest The URL request used for the image request. @param urlRequest The URL request used for the image request.
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes.
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. @param success A block to be executed when the image request operation finishes successfully. This block has no return value and takes two arguments: the server response and the image. If the image was returned from cache, the response parameter will be `nil`.
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. @param failure A block object to be executed when the image request operation finishes unsuccessfully, or that finishes successfully. This block has no return value and takes a single argument: the error that occurred.
*/ */
- (void)setImageForState:(UIControlState)state - (void)setImageForState:(UIControlState)state
withURLRequest:(NSURLRequest *)urlRequest withURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(nullable UIImage *)placeholderImage placeholderImage:(nullable UIImage *)placeholderImage
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, UIImage *image))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; failure:(nullable void (^)(NSError *error))failure;
///------------------------------- ///-------------------------------
...@@ -140,14 +151,14 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -140,14 +151,14 @@ NS_ASSUME_NONNULL_BEGIN
@param state The control state. @param state The control state.
@param urlRequest The URL request used for the image request. @param urlRequest The URL request used for the image request.
@param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes.
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. @param success A block to be executed when the image request operation finishes successfully. This block has no return value and takes two arguments: the server response and the image. If the image was returned from cache, the response parameter will be `nil`.
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. @param failure A block object to be executed when the image request operation finishes unsuccessfully, or that finishes successfully. This block has no return value and takes a single argument: the error that occurred.
*/ */
- (void)setBackgroundImageForState:(UIControlState)state - (void)setBackgroundImageForState:(UIControlState)state
withURLRequest:(NSURLRequest *)urlRequest withURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(nullable UIImage *)placeholderImage placeholderImage:(nullable UIImage *)placeholderImage
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, UIImage *image))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; failure:(nullable void (^)(NSError *error))failure;
///------------------------------ ///------------------------------
...@@ -155,18 +166,18 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -155,18 +166,18 @@ NS_ASSUME_NONNULL_BEGIN
///------------------------------ ///------------------------------
/** /**
Cancels any executing image task for the specified control state of the receiver, if one exists. Cancels any executing image operation for the specified control state of the receiver, if one exists.
@param state The control state. @param state The control state.
*/ */
- (void)cancelImageDownloadTaskForState:(UIControlState)state; - (void)cancelImageRequestOperationForState:(UIControlState)state;
/** /**
Cancels any executing background image task for the specified control state of the receiver, if one exists. Cancels any executing background image operation for the specified control state of the receiver, if one exists.
@param state The control state. @param state The control state.
*/ */
- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state; - (void)cancelBackgroundImageRequestOperationForState:(UIControlState)state;
@end @end
......
// UIButton+AFNetworking.m // UIButton+AFNetworking.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -23,76 +23,89 @@ ...@@ -23,76 +23,89 @@
#import <objc/runtime.h> #import <objc/runtime.h>
#if TARGET_OS_IOS || TARGET_OS_TV #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import "AFURLResponseSerialization.h"
#import "AFHTTPRequestOperation.h"
#import "UIImageView+AFNetworking.h" #import "UIImageView+AFNetworking.h"
#import "AFImageDownloader.h"
@interface UIButton (_AFNetworking) @interface UIButton (_AFNetworking)
@end @end
@implementation UIButton (_AFNetworking) @implementation UIButton (_AFNetworking)
+ (NSOperationQueue *)af_sharedImageRequestOperationQueue {
static NSOperationQueue *_af_sharedImageRequestOperationQueue = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_af_sharedImageRequestOperationQueue = [[NSOperationQueue alloc] init];
_af_sharedImageRequestOperationQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount;
});
return _af_sharedImageRequestOperationQueue;
}
#pragma mark - #pragma mark -
static char AFImageDownloadReceiptNormal; static char AFImageRequestOperationNormal;
static char AFImageDownloadReceiptHighlighted; static char AFImageRequestOperationHighlighted;
static char AFImageDownloadReceiptSelected; static char AFImageRequestOperationSelected;
static char AFImageDownloadReceiptDisabled; static char AFImageRequestOperationDisabled;
static const char * af_imageDownloadReceiptKeyForState(UIControlState state) { static const char * af_imageRequestOperationKeyForState(UIControlState state) {
switch (state) { switch (state) {
case UIControlStateHighlighted: case UIControlStateHighlighted:
return &AFImageDownloadReceiptHighlighted; return &AFImageRequestOperationHighlighted;
case UIControlStateSelected: case UIControlStateSelected:
return &AFImageDownloadReceiptSelected; return &AFImageRequestOperationSelected;
case UIControlStateDisabled: case UIControlStateDisabled:
return &AFImageDownloadReceiptDisabled; return &AFImageRequestOperationDisabled;
case UIControlStateNormal: case UIControlStateNormal:
default: default:
return &AFImageDownloadReceiptNormal; return &AFImageRequestOperationNormal;
} }
} }
- (AFImageDownloadReceipt *)af_imageDownloadReceiptForState:(UIControlState)state { - (AFHTTPRequestOperation *)af_imageRequestOperationForState:(UIControlState)state {
return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_imageDownloadReceiptKeyForState(state)); return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, af_imageRequestOperationKeyForState(state));
} }
- (void)af_setImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt - (void)af_setImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation
forState:(UIControlState)state forState:(UIControlState)state
{ {
objc_setAssociatedObject(self, af_imageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(self, af_imageRequestOperationKeyForState(state), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} }
#pragma mark - #pragma mark -
static char AFBackgroundImageDownloadReceiptNormal; static char AFBackgroundImageRequestOperationNormal;
static char AFBackgroundImageDownloadReceiptHighlighted; static char AFBackgroundImageRequestOperationHighlighted;
static char AFBackgroundImageDownloadReceiptSelected; static char AFBackgroundImageRequestOperationSelected;
static char AFBackgroundImageDownloadReceiptDisabled; static char AFBackgroundImageRequestOperationDisabled;
static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState state) { static const char * af_backgroundImageRequestOperationKeyForState(UIControlState state) {
switch (state) { switch (state) {
case UIControlStateHighlighted: case UIControlStateHighlighted:
return &AFBackgroundImageDownloadReceiptHighlighted; return &AFBackgroundImageRequestOperationHighlighted;
case UIControlStateSelected: case UIControlStateSelected:
return &AFBackgroundImageDownloadReceiptSelected; return &AFBackgroundImageRequestOperationSelected;
case UIControlStateDisabled: case UIControlStateDisabled:
return &AFBackgroundImageDownloadReceiptDisabled; return &AFBackgroundImageRequestOperationDisabled;
case UIControlStateNormal: case UIControlStateNormal:
default: default:
return &AFBackgroundImageDownloadReceiptNormal; return &AFBackgroundImageRequestOperationNormal;
} }
} }
- (AFImageDownloadReceipt *)af_backgroundImageDownloadReceiptForState:(UIControlState)state { - (AFHTTPRequestOperation *)af_backgroundImageRequestOperationForState:(UIControlState)state {
return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state)); return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, af_backgroundImageRequestOperationKeyForState(state));
} }
- (void)af_setBackgroundImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt - (void)af_setBackgroundImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation
forState:(UIControlState)state forState:(UIControlState)state
{ {
objc_setAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(self, af_backgroundImageRequestOperationKeyForState(state), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} }
@end @end
...@@ -101,13 +114,34 @@ static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState ...@@ -101,13 +114,34 @@ static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState
@implementation UIButton (AFNetworking) @implementation UIButton (AFNetworking)
+ (AFImageDownloader *)sharedImageDownloader { + (id <AFImageCache>)sharedImageCache {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
return objc_getAssociatedObject(self, @selector(sharedImageCache)) ?: [UIImageView sharedImageCache];
#pragma clang diagnostic pop
}
return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; + (void)setSharedImageCache:(__nullable id <AFImageCache>)imageCache {
objc_setAssociatedObject(self, @selector(sharedImageCache), imageCache, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} }
+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { #pragma mark -
objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
- (id <AFURLResponseSerialization>)imageResponseSerializer {
static id <AFURLResponseSerialization> _af_defaultImageResponseSerializer = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_af_defaultImageResponseSerializer = [AFImageResponseSerializer serializer];
});
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
return objc_getAssociatedObject(self, @selector(imageResponseSerializer)) ?: _af_defaultImageResponseSerializer;
#pragma clang diagnostic pop
}
- (void)setImageResponseSerializer:(id <AFURLResponseSerialization>)serializer {
objc_setAssociatedObject(self, @selector(imageResponseSerializer), serializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} }
#pragma mark - #pragma mark -
...@@ -130,62 +164,49 @@ static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState ...@@ -130,62 +164,49 @@ static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState
- (void)setImageForState:(UIControlState)state - (void)setImageForState:(UIControlState)state
withURLRequest:(NSURLRequest *)urlRequest withURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(nullable UIImage *)placeholderImage placeholderImage:(UIImage *)placeholderImage
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, UIImage *image))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure failure:(void (^)(NSError *error))failure
{ {
if ([self isActiveTaskURLEqualToURLRequest:urlRequest forState:state]) { [self cancelImageRequestOperationForState:state];
return;
}
[self cancelImageDownloadTaskForState:state];
AFImageDownloader *downloader = [[self class] sharedImageDownloader];
id <AFImageRequestCache> imageCache = downloader.imageCache;
//Use the image from the image cache if it exists UIImage *cachedImage = [[[self class] sharedImageCache] cachedImageForRequest:urlRequest];
UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
if (cachedImage) { if (cachedImage) {
if (success) { if (success) {
success(urlRequest, nil, cachedImage); success(urlRequest, nil, cachedImage);
} else { } else {
[self setImage:cachedImage forState:state]; [self setImage:cachedImage forState:state];
} }
[self af_setImageDownloadReceipt:nil forState:state];
[self af_setImageRequestOperation:nil forState:state];
} else { } else {
if (placeholderImage) { if (placeholderImage) {
[self setImage:placeholderImage forState:state]; [self setImage:placeholderImage forState:state];
} }
__weak __typeof(self)weakSelf = self; __weak __typeof(self)weakSelf = self;
NSUUID *downloadID = [NSUUID UUID]; AFHTTPRequestOperation *imageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
AFImageDownloadReceipt *receipt; imageRequestOperation.responseSerializer = self.imageResponseSerializer;
receipt = [downloader [imageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id __nullable responseObject) {
downloadImageForURLRequest:urlRequest __strong __typeof(weakSelf)strongSelf = weakSelf;
withReceiptID:downloadID if ([[urlRequest URL] isEqual:[operation.request URL]]) {
success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { if (success) {
__strong __typeof(weakSelf)strongSelf = weakSelf; success(operation.request, operation.response, responseObject);
if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { } else if (responseObject) {
if (success) { [strongSelf setImage:responseObject forState:state];
success(request, response, responseObject); }
} else if(responseObject) { }
[strongSelf setImage:responseObject forState:state]; [[[strongSelf class] sharedImageCache] cacheImage:responseObject forRequest:urlRequest];
} } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[strongSelf af_setImageDownloadReceipt:nil forState:state]; if ([[urlRequest URL] isEqual:[operation.request URL]]) {
} if (failure) {
failure(error);
} }
failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { }
__strong __typeof(weakSelf)strongSelf = weakSelf; }];
if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
if (failure) { [self af_setImageRequestOperation:imageRequestOperation forState:state];
failure(request, response, error); [[[self class] af_sharedImageRequestOperationQueue] addOperation:imageRequestOperation];
}
[strongSelf af_setImageDownloadReceipt:nil forState:state];
}
}];
[self af_setImageDownloadReceipt:receipt forState:state];
} }
} }
...@@ -199,7 +220,7 @@ static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState ...@@ -199,7 +220,7 @@ static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState
- (void)setBackgroundImageForState:(UIControlState)state - (void)setBackgroundImageForState:(UIControlState)state
withURL:(NSURL *)url withURL:(NSURL *)url
placeholderImage:(nullable UIImage *)placeholderImage placeholderImage:(UIImage *)placeholderImage
{ {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
...@@ -209,94 +230,64 @@ static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState ...@@ -209,94 +230,64 @@ static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState
- (void)setBackgroundImageForState:(UIControlState)state - (void)setBackgroundImageForState:(UIControlState)state
withURLRequest:(NSURLRequest *)urlRequest withURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(nullable UIImage *)placeholderImage placeholderImage:(UIImage *)placeholderImage
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, UIImage *image))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure failure:(void (^)(NSError *error))failure
{ {
if ([self isActiveBackgroundTaskURLEqualToURLRequest:urlRequest forState:state]) { [self cancelBackgroundImageRequestOperationForState:state];
return;
}
[self cancelBackgroundImageDownloadTaskForState:state];
AFImageDownloader *downloader = [[self class] sharedImageDownloader]; UIImage *cachedImage = [[[self class] sharedImageCache] cachedImageForRequest:urlRequest];
id <AFImageRequestCache> imageCache = downloader.imageCache;
//Use the image from the image cache if it exists
UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
if (cachedImage) { if (cachedImage) {
if (success) { if (success) {
success(urlRequest, nil, cachedImage); success(urlRequest, nil, cachedImage);
} else { } else {
[self setBackgroundImage:cachedImage forState:state]; [self setBackgroundImage:cachedImage forState:state];
} }
[self af_setBackgroundImageDownloadReceipt:nil forState:state];
[self af_setBackgroundImageRequestOperation:nil forState:state];
} else { } else {
if (placeholderImage) { if (placeholderImage) {
[self setBackgroundImage:placeholderImage forState:state]; [self setBackgroundImage:placeholderImage forState:state];
} }
__weak __typeof(self)weakSelf = self; __weak __typeof(self)weakSelf = self;
NSUUID *downloadID = [NSUUID UUID]; AFHTTPRequestOperation *backgroundImageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
AFImageDownloadReceipt *receipt; backgroundImageRequestOperation.responseSerializer = self.imageResponseSerializer;
receipt = [downloader [backgroundImageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id __nullable responseObject) {
downloadImageForURLRequest:urlRequest __strong __typeof(weakSelf)strongSelf = weakSelf;
withReceiptID:downloadID if ([[urlRequest URL] isEqual:[operation.request URL]]) {
success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { if (success) {
__strong __typeof(weakSelf)strongSelf = weakSelf; success(operation.request, operation.response, responseObject);
if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { } else if (responseObject) {
if (success) { [strongSelf setBackgroundImage:responseObject forState:state];
success(request, response, responseObject); }
} else if(responseObject) { }
[strongSelf setBackgroundImage:responseObject forState:state]; [[[strongSelf class] sharedImageCache] cacheImage:responseObject forRequest:urlRequest];
} } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state]; if ([[urlRequest URL] isEqual:[operation.request URL]]) {
} if (failure) {
failure(error);
} }
failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { }
__strong __typeof(weakSelf)strongSelf = weakSelf; }];
if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
if (failure) { [self af_setBackgroundImageRequestOperation:backgroundImageRequestOperation forState:state];
failure(request, response, error); [[[self class] af_sharedImageRequestOperationQueue] addOperation:backgroundImageRequestOperation];
}
[strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state];
}
}];
[self af_setBackgroundImageDownloadReceipt:receipt forState:state];
} }
} }
#pragma mark - #pragma mark -
- (void)cancelImageDownloadTaskForState:(UIControlState)state { - (void)cancelImageRequestOperationForState:(UIControlState)state {
AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state]; [[self af_imageRequestOperationForState:state] cancel];
if (receipt != nil) { [self af_setImageRequestOperation:nil forState:state];
[[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt];
[self af_setImageDownloadReceipt:nil forState:state];
}
}
- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state {
AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state];
if (receipt != nil) {
[[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt];
[self af_setBackgroundImageDownloadReceipt:nil forState:state];
}
}
- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state {
AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state];
return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString];
} }
- (BOOL)isActiveBackgroundTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state { - (void)cancelBackgroundImageRequestOperationForState:(UIControlState)state {
AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state]; [[self af_backgroundImageRequestOperationForState:state] cancel];
return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; [self af_setBackgroundImageRequestOperation:nil forState:state];
} }
@end @end
#endif #endif
...@@ -22,7 +22,7 @@ ...@@ -22,7 +22,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
#if TARGET_OS_IOS || TARGET_OS_TV #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
......
// UIImageView+AFNetworking.h // UIImageView+AFNetworking.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -21,36 +21,47 @@ ...@@ -21,36 +21,47 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <TargetConditionals.h> #import <Availability.h>
#if TARGET_OS_IOS || TARGET_OS_TV #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
@class AFImageDownloader; @protocol AFURLResponseSerialization, AFImageCache;
/** /**
This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL. This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL.
*/ */
@interface UIImageView (AFNetworking) @interface UIImageView (AFNetworking)
///------------------------------------ ///----------------------------
/// @name Accessing the Image Downloader /// @name Accessing Image Cache
///------------------------------------ ///----------------------------
/**
The image cache used to improve image loading performance on scroll views. By default, this is an `NSCache` subclass conforming to the `AFImageCache` protocol, which listens for notification warnings and evicts objects accordingly.
*/
+ (id <AFImageCache>)sharedImageCache;
/** /**
Set the shared image downloader used to download images. Set the cache used for image loading.
@param imageDownloader The shared image downloader used to download images. @param imageCache The image cache.
*/ */
+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; + (void)setSharedImageCache:(__nullable id <AFImageCache>)imageCache;
///------------------------------------
/// @name Accessing Response Serializer
///------------------------------------
/** /**
The shared image downloader used to download images. The response serializer used to create an image representation from the server response and response data. By default, this is an instance of `AFImageResponseSerializer`.
@discussion Subclasses of `AFImageResponseSerializer` could be used to perform post-processing, such as color correction, face detection, or other effects. See https://github.com/AFNetworking/AFCoreImageSerializer
*/ */
+ (AFImageDownloader *)sharedImageDownloader; @property (nonatomic, strong) id <AFURLResponseSerialization> imageResponseSerializer;
///-------------------- ///--------------------
/// @name Setting Image /// @name Setting Image
...@@ -89,19 +100,45 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -89,19 +100,45 @@ NS_ASSUME_NONNULL_BEGIN
@param urlRequest The URL request used for the image request. @param urlRequest The URL request used for the image request.
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. @param success A block to be executed when the image request operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. @param failure A block object to be executed when the image request operation finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
*/ */
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(nullable UIImage *)placeholderImage placeholderImage:(nullable UIImage *)placeholderImage
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, UIImage *image))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, NSError *error))failure;
/** /**
Cancels any executing image operation for the receiver, if one exists. Cancels any executing image operation for the receiver, if one exists.
*/ */
- (void)cancelImageDownloadTask; - (void)cancelImageRequestOperation;
@end
#pragma mark -
/**
The `AFImageCache` protocol is adopted by an object used to cache images loaded by the AFNetworking category on `UIImageView`.
*/
@protocol AFImageCache <NSObject>
/**
Returns a cached image for the specified request, if available.
@param request The image request.
@return The cached image.
*/
- (nullable UIImage *)cachedImageForRequest:(NSURLRequest *)request;
/**
Caches a particular image for the specified request.
@param image The image to cache.
@param request The request to be used as a cache key.
*/
- (void)cacheImage:(UIImage *)image
forRequest:(NSURLRequest *)request;
@end @end
NS_ASSUME_NONNULL_END NS_ASSUME_NONNULL_END
......
// UIImageView+AFNetworking.m // UIImageView+AFNetworking.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -23,22 +23,38 @@ ...@@ -23,22 +23,38 @@
#import <objc/runtime.h> #import <objc/runtime.h>
#if TARGET_OS_IOS || TARGET_OS_TV #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import "AFImageDownloader.h" #import "AFHTTPRequestOperation.h"
@interface AFImageCache : NSCache <AFImageCache>
@end
#pragma mark -
@interface UIImageView (_AFNetworking) @interface UIImageView (_AFNetworking)
@property (readwrite, nonatomic, strong, setter = af_setActiveImageDownloadReceipt:) AFImageDownloadReceipt *af_activeImageDownloadReceipt; @property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFHTTPRequestOperation *af_imageRequestOperation;
@end @end
@implementation UIImageView (_AFNetworking) @implementation UIImageView (_AFNetworking)
- (AFImageDownloadReceipt *)af_activeImageDownloadReceipt { + (NSOperationQueue *)af_sharedImageRequestOperationQueue {
return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(af_activeImageDownloadReceipt)); static NSOperationQueue *_af_sharedImageRequestOperationQueue = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_af_sharedImageRequestOperationQueue = [[NSOperationQueue alloc] init];
_af_sharedImageRequestOperationQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount;
});
return _af_sharedImageRequestOperationQueue;
}
- (AFHTTPRequestOperation *)af_imageRequestOperation {
return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, @selector(af_imageRequestOperation));
} }
- (void)af_setActiveImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt { - (void)af_setImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation {
objc_setAssociatedObject(self, @selector(af_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(self, @selector(af_imageRequestOperation), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} }
@end @end
...@@ -46,13 +62,46 @@ ...@@ -46,13 +62,46 @@
#pragma mark - #pragma mark -
@implementation UIImageView (AFNetworking) @implementation UIImageView (AFNetworking)
@dynamic imageResponseSerializer;
+ (id <AFImageCache>)sharedImageCache {
static AFImageCache *_af_defaultImageCache = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_af_defaultImageCache = [[AFImageCache alloc] init];
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidReceiveMemoryWarningNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * __unused notification) {
[_af_defaultImageCache removeAllObjects];
}];
});
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
return objc_getAssociatedObject(self, @selector(sharedImageCache)) ?: _af_defaultImageCache;
#pragma clang diagnostic pop
}
+ (AFImageDownloader *)sharedImageDownloader { + (void)setSharedImageCache:(__nullable id <AFImageCache>)imageCache {
return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; objc_setAssociatedObject(self, @selector(sharedImageCache), imageCache, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} }
+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { #pragma mark -
objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
- (id <AFURLResponseSerialization>)imageResponseSerializer {
static id <AFURLResponseSerialization> _af_defaultImageResponseSerializer = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_af_defaultImageResponseSerializer = [AFImageResponseSerializer serializer];
});
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
return objc_getAssociatedObject(self, @selector(imageResponseSerializer)) ?: _af_defaultImageResponseSerializer;
#pragma clang diagnostic pop
}
- (void)setImageResponseSerializer:(id <AFURLResponseSerialization>)serializer {
objc_setAssociatedObject(self, @selector(imageResponseSerializer), serializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} }
#pragma mark - #pragma mark -
...@@ -72,87 +121,93 @@ ...@@ -72,87 +121,93 @@
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(UIImage *)placeholderImage placeholderImage:(UIImage *)placeholderImage
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, NSError *error))failure
{ {
[self cancelImageRequestOperation];
if ([urlRequest URL] == nil) {
self.image = placeholderImage;
if (failure) {
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil];
failure(urlRequest, nil, error);
}
return;
}
if ([self isActiveTaskURLEqualToURLRequest:urlRequest]){
return;
}
[self cancelImageDownloadTask];
AFImageDownloader *downloader = [[self class] sharedImageDownloader];
id <AFImageRequestCache> imageCache = downloader.imageCache;
//Use the image from the image cache if it exists UIImage *cachedImage = [[[self class] sharedImageCache] cachedImageForRequest:urlRequest];
UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
if (cachedImage) { if (cachedImage) {
if (success) { if (success) {
success(urlRequest, nil, cachedImage); success(urlRequest, nil, cachedImage);
} else { } else {
self.image = cachedImage; self.image = cachedImage;
} }
[self clearActiveDownloadInformation];
self.af_imageRequestOperation = nil;
} else { } else {
if (placeholderImage) { if (placeholderImage) {
self.image = placeholderImage; self.image = placeholderImage;
} }
__weak __typeof(self)weakSelf = self; __weak __typeof(self)weakSelf = self;
NSUUID *downloadID = [NSUUID UUID]; self.af_imageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
AFImageDownloadReceipt *receipt; self.af_imageRequestOperation.responseSerializer = self.imageResponseSerializer;
receipt = [downloader [self.af_imageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id __nullable responseObject) {
downloadImageForURLRequest:urlRequest __strong __typeof(weakSelf)strongSelf = weakSelf;
withReceiptID:downloadID if ([[urlRequest URL] isEqual:[strongSelf.af_imageRequestOperation.request URL]]) {
success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { if (success) {
__strong __typeof(weakSelf)strongSelf = weakSelf; success(urlRequest, operation.response, responseObject);
if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { } else if (responseObject) {
if (success) { strongSelf.image = responseObject;
success(request, response, responseObject); }
} else if(responseObject) {
strongSelf.image = responseObject; if (operation == strongSelf.af_imageRequestOperation){
} strongSelf.af_imageRequestOperation = nil;
[strongSelf clearActiveDownloadInformation]; }
} }
} [[[strongSelf class] sharedImageCache] cacheImage:responseObject forRequest:urlRequest];
failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
__strong __typeof(weakSelf)strongSelf = weakSelf; __strong __typeof(weakSelf)strongSelf = weakSelf;
if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { if ([[urlRequest URL] isEqual:[strongSelf.af_imageRequestOperation.request URL]]) {
if (failure) { if (failure) {
failure(request, response, error); failure(urlRequest, operation.response, error);
} }
[strongSelf clearActiveDownloadInformation];
} if (operation == strongSelf.af_imageRequestOperation){
}]; strongSelf.af_imageRequestOperation = nil;
}
self.af_activeImageDownloadReceipt = receipt; }
}];
[[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation];
} }
} }
- (void)cancelImageDownloadTask { - (void)cancelImageRequestOperation {
if (self.af_activeImageDownloadReceipt != nil) { [self.af_imageRequestOperation cancel];
[[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt]; self.af_imageRequestOperation = nil;
[self clearActiveDownloadInformation]; }
}
@end
#pragma mark -
static inline NSString * AFImageCacheKeyFromURLRequest(NSURLRequest *request) {
return [[request URL] absoluteString];
} }
- (void)clearActiveDownloadInformation { @implementation AFImageCache
self.af_activeImageDownloadReceipt = nil;
- (UIImage *)cachedImageForRequest:(NSURLRequest *)request {
switch ([request cachePolicy]) {
case NSURLRequestReloadIgnoringCacheData:
case NSURLRequestReloadIgnoringLocalAndRemoteCacheData:
return nil;
default:
break;
}
return [self objectForKey:AFImageCacheKeyFromURLRequest(request)];
} }
- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest { - (void)cacheImage:(UIImage *)image
return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; forRequest:(NSURLRequest *)request
{
if (image && request) {
[self setObject:image forKey:AFImageCacheKeyFromURLRequest(request)];
}
} }
@end @end
......
// UIKit+AFNetworking.h // UIKit+AFNetworking.h
// //
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2013 AFNetworking (http://afnetworking.com/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -20,23 +20,20 @@ ...@@ -20,23 +20,20 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
#if TARGET_OS_IOS || TARGET_OS_TV #if TARGET_OS_IOS
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
#ifndef _UIKIT_AFNETWORKING_ #ifndef _UIKIT_AFNETWORKING_
#define _UIKIT_AFNETWORKING_ #define _UIKIT_AFNETWORKING_
#if TARGET_OS_IOS
#import "AFAutoPurgingImageCache.h"
#import "AFImageDownloader.h"
#import "AFNetworkActivityIndicatorManager.h" #import "AFNetworkActivityIndicatorManager.h"
#import "UIRefreshControl+AFNetworking.h"
#import "UIWebView+AFNetworking.h"
#endif
#import "UIActivityIndicatorView+AFNetworking.h" #import "UIActivityIndicatorView+AFNetworking.h"
#import "UIAlertView+AFNetworking.h"
#import "UIButton+AFNetworking.h" #import "UIButton+AFNetworking.h"
#import "UIImageView+AFNetworking.h" #import "UIImageView+AFNetworking.h"
#import "UIProgressView+AFNetworking.h" #import "UIProgressView+AFNetworking.h"
#import "UIRefreshControl+AFNetworking.h"
#import "UIWebView+AFNetworking.h"
#endif /* _UIKIT_AFNETWORKING_ */ #endif /* _UIKIT_AFNETWORKING_ */
#endif #endif
// UIProgressView+AFNetworking.h // UIProgressView+AFNetworking.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -21,17 +21,18 @@ ...@@ -21,17 +21,18 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <TargetConditionals.h> #import <Availability.h>
#if TARGET_OS_IOS || TARGET_OS_TV #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
@class AFURLConnectionOperation;
/** /**
This category adds methods to the UIKit framework's `UIProgressView` class. The methods in this category provide support for binding the progress to the upload and download progress of a session task. This category adds methods to the UIKit framework's `UIProgressView` class. The methods in this category provide support for binding the progress to the upload and download progress of a session task or request operation.
*/ */
@interface UIProgressView (AFNetworking) @interface UIProgressView (AFNetworking)
...@@ -45,8 +46,10 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -45,8 +46,10 @@ NS_ASSUME_NONNULL_BEGIN
@param task The session task. @param task The session task.
@param animated `YES` if the change should be animated, `NO` if the change should happen immediately. @param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
*/ */
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task - (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
animated:(BOOL)animated; animated:(BOOL)animated;
#endif
/** /**
Binds the progress to the download progress of the specified session task. Binds the progress to the download progress of the specified session task.
...@@ -54,8 +57,32 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -54,8 +57,32 @@ NS_ASSUME_NONNULL_BEGIN
@param task The session task. @param task The session task.
@param animated `YES` if the change should be animated, `NO` if the change should happen immediately. @param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
*/ */
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task - (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
animated:(BOOL)animated; animated:(BOOL)animated;
#endif
///------------------------------------
/// @name Setting Session Task Progress
///------------------------------------
/**
Binds the progress to the upload progress of the specified request operation.
@param operation The request operation.
@param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
*/
- (void)setProgressWithUploadProgressOfOperation:(AFURLConnectionOperation *)operation
animated:(BOOL)animated;
/**
Binds the progress to the download progress of the specified request operation.
@param operation The request operation.
@param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
*/
- (void)setProgressWithDownloadProgressOfOperation:(AFURLConnectionOperation *)operation
animated:(BOOL)animated;
@end @end
......
// UIProgressView+AFNetworking.m // UIProgressView+AFNetworking.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -23,13 +23,33 @@ ...@@ -23,13 +23,33 @@
#import <objc/runtime.h> #import <objc/runtime.h>
#if TARGET_OS_IOS || TARGET_OS_TV #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import "AFURLConnectionOperation.h"
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
#import "AFURLSessionManager.h" #import "AFURLSessionManager.h"
#endif
static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext; static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext;
static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext; static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext;
@interface AFURLConnectionOperation (_UIProgressView)
@property (readwrite, nonatomic, copy) void (^uploadProgress)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected);
@property (readwrite, nonatomic, assign, setter = af_setUploadProgressAnimated:) BOOL af_uploadProgressAnimated;
@property (readwrite, nonatomic, copy) void (^downloadProgress)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected);
@property (readwrite, nonatomic, assign, setter = af_setDownloadProgressAnimated:) BOOL af_downloadProgressAnimated;
@end
@implementation AFURLConnectionOperation (_UIProgressView)
@dynamic uploadProgress; // Implemented in AFURLConnectionOperation
@dynamic af_uploadProgressAnimated;
@dynamic downloadProgress; // Implemented in AFURLConnectionOperation
@dynamic af_downloadProgressAnimated;
@end
#pragma mark - #pragma mark -
@implementation UIProgressView (AFNetworking) @implementation UIProgressView (AFNetworking)
...@@ -52,13 +72,10 @@ static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedCon ...@@ -52,13 +72,10 @@ static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedCon
#pragma mark - #pragma mark -
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task - (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
animated:(BOOL)animated animated:(BOOL)animated
{ {
if (task.state == NSURLSessionTaskStateCompleted) {
return;
}
[task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext];
[task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; [task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext];
...@@ -68,15 +85,52 @@ static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedCon ...@@ -68,15 +85,52 @@ static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedCon
- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task - (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
animated:(BOOL)animated animated:(BOOL)animated
{ {
if (task.state == NSURLSessionTaskStateCompleted) {
return;
}
[task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext];
[task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; [task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext];
[self af_setDownloadProgressAnimated:animated]; [self af_setDownloadProgressAnimated:animated];
} }
#endif
#pragma mark -
- (void)setProgressWithUploadProgressOfOperation:(AFURLConnectionOperation *)operation
animated:(BOOL)animated
{
__weak __typeof(self)weakSelf = self;
void (^original)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) = [operation.uploadProgress copy];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
if (original) {
original(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}
dispatch_async(dispatch_get_main_queue(), ^{
if (totalBytesExpectedToWrite > 0) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
[strongSelf setProgress:(totalBytesWritten / (totalBytesExpectedToWrite * 1.0f)) animated:animated];
}
});
}];
}
- (void)setProgressWithDownloadProgressOfOperation:(AFURLConnectionOperation *)operation
animated:(BOOL)animated
{
__weak __typeof(self)weakSelf = self;
void (^original)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) = [operation.downloadProgress copy];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
if (original) {
original(bytesRead, totalBytesRead, totalBytesExpectedToRead);
}
dispatch_async(dispatch_get_main_queue(), ^{
if (totalBytesExpectedToRead > 0) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
[strongSelf setProgress:(totalBytesRead / (totalBytesExpectedToRead * 1.0f)) animated:animated];
}
});
}];
}
#pragma mark - NSKeyValueObserving #pragma mark - NSKeyValueObserving
...@@ -85,6 +139,7 @@ static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedCon ...@@ -85,6 +139,7 @@ static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedCon
change:(__unused NSDictionary *)change change:(__unused NSDictionary *)change
context:(void *)context context:(void *)context
{ {
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) { if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) {
if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) { if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) {
if ([object countOfBytesExpectedToSend] > 0) { if ([object countOfBytesExpectedToSend] > 0) {
...@@ -119,6 +174,7 @@ static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedCon ...@@ -119,6 +174,7 @@ static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedCon
} }
} }
} }
#endif
} }
@end @end
......
// UIRefreshControl+AFNetworking.m // UIRefreshControl+AFNetworking.m
// //
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2014 AFNetworking (http://afnetworking.com)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -22,16 +22,18 @@ ...@@ -22,16 +22,18 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <TargetConditionals.h> #import <Availability.h>
#if TARGET_OS_IOS #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
@class AFURLConnectionOperation;
/** /**
This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically beginning and ending refreshing depending on the loading state of a session task. This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically beginning and ending refreshing depending on the loading state of a request operation or session task.
*/ */
@interface UIRefreshControl (AFNetworking) @interface UIRefreshControl (AFNetworking)
...@@ -44,7 +46,20 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -44,7 +46,20 @@ NS_ASSUME_NONNULL_BEGIN
@param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled.
*/ */
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task;
#endif
///----------------------------------------
/// @name Refreshing for Request Operations
///----------------------------------------
/**
Binds the refreshing state to the execution state of the specified operation.
@param operation The operation. If `nil`, automatic updating from any previously specified operation will be disabled.
*/
- (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation;
@end @end
......
// UIRefreshControl+AFNetworking.m // UIRefreshControl+AFNetworking.m
// //
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2014 AFNetworking (http://afnetworking.com)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -23,15 +23,22 @@ ...@@ -23,15 +23,22 @@
#import "UIRefreshControl+AFNetworking.h" #import "UIRefreshControl+AFNetworking.h"
#import <objc/runtime.h> #import <objc/runtime.h>
#if TARGET_OS_IOS #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import "AFHTTPRequestOperation.h"
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
#import "AFURLSessionManager.h" #import "AFURLSessionManager.h"
#endif
@interface AFRefreshControlNotificationObserver : NSObject @interface AFRefreshControlNotificationObserver : NSObject
@property (readonly, nonatomic, weak) UIRefreshControl *refreshControl; @property (readonly, nonatomic, weak) UIRefreshControl *refreshControl;
- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl; - (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl;
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task;
#endif
- (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation;
@end @end
...@@ -46,9 +53,15 @@ ...@@ -46,9 +53,15 @@
return notificationObserver; return notificationObserver;
} }
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task {
[[self af_notificationObserver] setRefreshingWithStateOfTask:task]; [[self af_notificationObserver] setRefreshingWithStateOfTask:task];
} }
#endif
- (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation {
[[self af_notificationObserver] setRefreshingWithStateOfOperation:operation];
}
@end @end
...@@ -63,6 +76,7 @@ ...@@ -63,6 +76,7 @@
return self; return self;
} }
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
...@@ -71,16 +85,44 @@ ...@@ -71,16 +85,44 @@
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
if (task) { if (task) {
UIRefreshControl *refreshControl = self.refreshControl; #pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreceiver-is-weak"
#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak"
if (task.state == NSURLSessionTaskStateRunning) { if (task.state == NSURLSessionTaskStateRunning) {
[refreshControl beginRefreshing]; [self.refreshControl beginRefreshing];
[notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task]; [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task];
[notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task]; [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task];
[notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task]; [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task];
} else { } else {
[refreshControl endRefreshing]; [self.refreshControl endRefreshing];
} }
#pragma clang diagnostic pop
}
}
#endif
- (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil];
if (operation) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreceiver-is-weak"
#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak"
if (![operation isFinished]) {
if ([operation isExecuting]) {
[self.refreshControl beginRefreshing];
} else {
[self.refreshControl endRefreshing];
}
[notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingOperationDidStartNotification object:operation];
[notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingOperationDidFinishNotification object:operation];
}
#pragma clang diagnostic pop
} }
} }
...@@ -88,13 +130,19 @@ ...@@ -88,13 +130,19 @@
- (void)af_beginRefreshing { - (void)af_beginRefreshing {
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreceiver-is-weak"
[self.refreshControl beginRefreshing]; [self.refreshControl beginRefreshing];
#pragma clang diagnostic pop
}); });
} }
- (void)af_endRefreshing { - (void)af_endRefreshing {
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreceiver-is-weak"
[self.refreshControl endRefreshing]; [self.refreshControl endRefreshing];
#pragma clang diagnostic pop
}); });
} }
...@@ -103,9 +151,14 @@ ...@@ -103,9 +151,14 @@
- (void)dealloc { - (void)dealloc {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
#endif
[notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil];
} }
@end @end
......
// UIWebView+AFNetworking.h // UIWebView+AFNetworking.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -21,15 +21,16 @@ ...@@ -21,15 +21,16 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <TargetConditionals.h> #import <Availability.h>
#if TARGET_OS_IOS #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
@class AFHTTPSessionManager; @class AFHTTPRequestSerializer, AFHTTPResponseSerializer;
@protocol AFURLRequestSerialization, AFURLResponseSerialization;
/** /**
This category adds methods to the UIKit framework's `UIWebView` class. The methods in this category provide increased control over the request cycle, including progress monitoring and success / failure handling. This category adds methods to the UIKit framework's `UIWebView` class. The methods in this category provide increased control over the request cycle, including progress monitoring and success / failure handling.
...@@ -39,20 +40,25 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -39,20 +40,25 @@ NS_ASSUME_NONNULL_BEGIN
@interface UIWebView (AFNetworking) @interface UIWebView (AFNetworking)
/** /**
The session manager used to download all requests. The request serializer used to serialize requests made with the `-loadRequest:...` category methods. By default, this is an instance of `AFHTTPRequestSerializer`.
*/ */
@property (nonatomic, strong) AFHTTPSessionManager *sessionManager; @property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
/**
The response serializer used to serialize responses made with the `-loadRequest:...` category methods. By default, this is an instance of `AFHTTPResponseSerializer`.
*/
@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
/** /**
Asynchronously loads the specified request. Asynchronously loads the specified request.
@param request A URL request identifying the location of the content to load. This must not be `nil`. @param request A URL request identifying the location of the content to load. This must not be `nil`.
@param progress A progress object monitoring the current download progress. @param progress A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread.
@param success A block object to be executed when the request finishes loading successfully. This block returns the HTML string to be loaded by the web view, and takes two arguments: the response, and the response string. @param success A block object to be executed when the request finishes loading successfully. This block returns the HTML string to be loaded by the web view, and takes two arguments: the response, and the response string.
@param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred. @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred.
*/ */
- (void)loadRequest:(NSURLRequest *)request - (void)loadRequest:(NSURLRequest *)request
progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress progress:(nullable void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress
success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
failure:(nullable void (^)(NSError *error))failure; failure:(nullable void (^)(NSError *error))failure;
...@@ -62,14 +68,14 @@ NS_ASSUME_NONNULL_BEGIN ...@@ -62,14 +68,14 @@ NS_ASSUME_NONNULL_BEGIN
@param request A URL request identifying the location of the content to load. This must not be `nil`. @param request A URL request identifying the location of the content to load. This must not be `nil`.
@param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified. @param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified.
@param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified. @param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified.
@param progress A progress object monitoring the current download progress. @param progress A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread.
@param success A block object to be executed when the request finishes loading successfully. This block returns the data to be loaded by the web view and takes two arguments: the response, and the downloaded data. @param success A block object to be executed when the request finishes loading successfully. This block returns the data to be loaded by the web view and takes two arguments: the response, and the downloaded data.
@param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred. @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred.
*/ */
- (void)loadRequest:(NSURLRequest *)request - (void)loadRequest:(NSURLRequest *)request
MIMEType:(nullable NSString *)MIMEType MIMEType:(nullable NSString *)MIMEType
textEncodingName:(nullable NSString *)textEncodingName textEncodingName:(nullable NSString *)textEncodingName
progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress progress:(nullable void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress
success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
failure:(nullable void (^)(NSError *error))failure; failure:(nullable void (^)(NSError *error))failure;
......
// UIWebView+AFNetworking.m // UIWebView+AFNetworking.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
...@@ -23,24 +23,24 @@ ...@@ -23,24 +23,24 @@
#import <objc/runtime.h> #import <objc/runtime.h>
#if TARGET_OS_IOS #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import "AFHTTPSessionManager.h" #import "AFHTTPRequestOperation.h"
#import "AFURLResponseSerialization.h" #import "AFURLResponseSerialization.h"
#import "AFURLRequestSerialization.h" #import "AFURLRequestSerialization.h"
@interface UIWebView (_AFNetworking) @interface UIWebView (_AFNetworking)
@property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask; @property (readwrite, nonatomic, strong, setter = af_setHTTPRequestOperation:) AFHTTPRequestOperation *af_HTTPRequestOperation;
@end @end
@implementation UIWebView (_AFNetworking) @implementation UIWebView (_AFNetworking)
- (NSURLSessionDataTask *)af_URLSessionTask { - (AFHTTPRequestOperation *)af_HTTPRequestOperation {
return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask)); return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, @selector(af_HTTPRequestOperation));
} }
- (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask { - (void)af_setHTTPRequestOperation:(AFHTTPRequestOperation *)operation {
objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(self, @selector(af_HTTPRequestOperation), operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} }
@end @end
...@@ -49,20 +49,21 @@ ...@@ -49,20 +49,21 @@
@implementation UIWebView (AFNetworking) @implementation UIWebView (AFNetworking)
- (AFHTTPSessionManager *)sessionManager { - (AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil; static AFHTTPRequestSerializer <AFURLRequestSerialization> *_af_defaultRequestSerializer = nil;
static dispatch_once_t onceToken; static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ dispatch_once(&onceToken, ^{
_af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; _af_defaultRequestSerializer = [AFHTTPRequestSerializer serializer];
_af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
_af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
}); });
return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager; #pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
return objc_getAssociatedObject(self, @selector(requestSerializer)) ?: _af_defaultRequestSerializer;
#pragma clang diagnostic pop
} }
- (void)setSessionManager:(AFHTTPSessionManager *)sessionManager { - (void)setRequestSerializer:(AFHTTPRequestSerializer<AFURLRequestSerialization> *)requestSerializer {
objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(self, @selector(requestSerializer), requestSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} }
- (AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer { - (AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
...@@ -72,7 +73,10 @@ ...@@ -72,7 +73,10 @@
_af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer]; _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer];
}); });
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer; return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer;
#pragma clang diagnostic pop
} }
- (void)setResponseSerializer:(AFHTTPResponseSerializer<AFURLResponseSerialization> *)responseSerializer { - (void)setResponseSerializer:(AFHTTPResponseSerializer<AFURLResponseSerialization> *)responseSerializer {
...@@ -82,7 +86,7 @@ ...@@ -82,7 +86,7 @@
#pragma mark - #pragma mark -
- (void)loadRequest:(NSURLRequest *)request - (void)loadRequest:(NSURLRequest *)request
progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress progress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress
success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
failure:(void (^)(NSError *error))failure failure:(void (^)(NSError *error))failure
{ {
...@@ -107,45 +111,43 @@ ...@@ -107,45 +111,43 @@
- (void)loadRequest:(NSURLRequest *)request - (void)loadRequest:(NSURLRequest *)request
MIMEType:(NSString *)MIMEType MIMEType:(NSString *)MIMEType
textEncodingName:(NSString *)textEncodingName textEncodingName:(NSString *)textEncodingName
progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress progress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress
success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
failure:(void (^)(NSError *error))failure failure:(void (^)(NSError *error))failure
{ {
NSParameterAssert(request); NSParameterAssert(request);
if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) { if (self.af_HTTPRequestOperation) {
[self.af_URLSessionTask cancel]; [self.af_HTTPRequestOperation cancel];
} }
self.af_URLSessionTask = nil;
request = [self.requestSerializer requestBySerializingRequest:request withParameters:nil error:nil];
self.af_HTTPRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
self.af_HTTPRequestOperation.responseSerializer = self.responseSerializer;
__weak __typeof(self)weakSelf = self; __weak __typeof(self)weakSelf = self;
__block NSURLSessionDataTask *dataTask; [self.af_HTTPRequestOperation setDownloadProgressBlock:progress];
dataTask = [self.sessionManager [self.af_HTTPRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id __unused responseObject) {
dataTaskWithRequest:request NSData *data = success ? success(operation.response, operation.responseData) : operation.responseData;
uploadProgress:nil
downloadProgress:nil #pragma clang diagnostic push
completionHandler:^(NSURLResponse * _Nonnull response, id _Nonnull responseObject, NSError * _Nullable error) { #pragma clang diagnostic ignored "-Wgnu"
__strong __typeof(weakSelf) strongSelf = weakSelf; __strong __typeof(weakSelf) strongSelf = weakSelf;
if (error) { [strongSelf loadData:data MIMEType:(MIMEType ?: [operation.response MIMEType]) textEncodingName:(textEncodingName ?: [operation.response textEncodingName]) baseURL:[operation.response URL]];
if (failure) {
failure(error); if ([strongSelf.delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
} [strongSelf.delegate webViewDidFinishLoad:strongSelf];
} else { }
if (success) {
success((NSHTTPURLResponse *)response, responseObject); #pragma clang diagnostic pop
} } failure:^(AFHTTPRequestOperation * __unused operation, NSError *error) {
[strongSelf loadData:responseObject MIMEType:MIMEType textEncodingName:textEncodingName baseURL:[dataTask.currentRequest URL]]; if (failure) {
failure(error);
if ([strongSelf.delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) { }
[strongSelf.delegate webViewDidFinishLoad:strongSelf]; }];
}
} [self.af_HTTPRequestOperation start];
}];
self.af_URLSessionTask = dataTask;
if (progress != nil) {
*progress = [self.sessionManager downloadProgressForTask:dataTask];
}
[self.af_URLSessionTask resume];
if ([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { if ([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
[self.delegate webViewDidStartLoad:self]; [self.delegate webViewDidStartLoad:self];
......
PODS: PODS:
- AFNetworking (3.2.1): - AFJSONRPCClient (2.1.1):
- AFNetworking/NSURLSession (= 3.2.1) - AFNetworking (~> 2.1)
- AFNetworking/Reachability (= 3.2.1) - AFNetworking (2.7.0):
- AFNetworking/Security (= 3.2.1) - AFNetworking/NSURLConnection (= 2.7.0)
- AFNetworking/Serialization (= 3.2.1) - AFNetworking/NSURLSession (= 2.7.0)
- AFNetworking/UIKit (= 3.2.1) - AFNetworking/Reachability (= 2.7.0)
- AFNetworking/NSURLSession (3.2.1): - AFNetworking/Security (= 2.7.0)
- AFNetworking/Serialization (= 2.7.0)
- AFNetworking/UIKit (= 2.7.0)
- AFNetworking/NSURLConnection (2.7.0):
- AFNetworking/Reachability - AFNetworking/Reachability
- AFNetworking/Security - AFNetworking/Security
- AFNetworking/Serialization - AFNetworking/Serialization
- AFNetworking/Reachability (3.2.1) - AFNetworking/NSURLSession (2.7.0):
- AFNetworking/Security (3.2.1) - AFNetworking/Reachability
- AFNetworking/Serialization (3.2.1) - AFNetworking/Security
- AFNetworking/UIKit (3.2.1): - AFNetworking/Serialization
- AFNetworking/Reachability (2.7.0)
- AFNetworking/Security (2.7.0)
- AFNetworking/Serialization (2.7.0)
- AFNetworking/UIKit (2.7.0):
- AFNetworking/NSURLConnection
- AFNetworking/NSURLSession - AFNetworking/NSURLSession
- IQKeyboardManager (6.5.6) - IQKeyboardManager (6.5.6)
- Masonry (1.1.0) - Masonry (1.1.0)
DEPENDENCIES: DEPENDENCIES:
- AFJSONRPCClient
- AFNetworking - AFNetworking
- IQKeyboardManager - IQKeyboardManager
- Masonry - Masonry
SPEC REPOS: SPEC REPOS:
https://github.com/CocoaPods/Specs.git: https://github.com/CocoaPods/Specs.git:
- AFJSONRPCClient
- AFNetworking - AFNetworking
- IQKeyboardManager - IQKeyboardManager
- Masonry - Masonry
SPEC CHECKSUMS: SPEC CHECKSUMS:
AFNetworking: b6f891fdfaed196b46c7a83cf209e09697b94057 AFJSONRPCClient: 333bada91e6e45398446b8bd84e238e6f2389b1b
AFNetworking: 8dd5f9b9691e09186393069a12cc3b5ed7c8b511
IQKeyboardManager: 2a6e97afdafc7becf0cb17a9a8d795e3a980717f IQKeyboardManager: 2a6e97afdafc7becf0cb17a9a8d795e3a980717f
Masonry: 678fab65091a9290e40e2832a55e7ab731aad201 Masonry: 678fab65091a9290e40e2832a55e7ab731aad201
PODFILE CHECKSUM: 05dc85bcfeedc8253c411e67a7ee98c5ff6bdd07 PODFILE CHECKSUM: c17dd2b51db38ebc1361046f88ac3934293eb4ef
COCOAPODS: 1.8.3 COCOAPODS: 1.8.3
This source diff could not be displayed because it is too large. You can view the blob instead.
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1100"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForAnalyzing = "YES"
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "3A7F4502B2215DA26D792623E9552CCD"
BuildableName = "AFJSONRPCClient.framework"
BlueprintName = "AFJSONRPCClient"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
buildConfiguration = "Debug"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES"
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
...@@ -4,6 +4,11 @@ ...@@ -4,6 +4,11 @@
<dict> <dict>
<key>SchemeUserState</key> <key>SchemeUserState</key>
<dict> <dict>
<key>AFJSONRPCClient.xcscheme</key>
<dict>
<key>isShown</key>
<false/>
</dict>
<key>AFNetworking.xcscheme</key> <key>AFNetworking.xcscheme</key>
<dict> <dict>
<key>isShown</key> <key>isShown</key>
......
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>${PRODUCT_BUNDLE_IDENTIFIER}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.1.1</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>${CURRENT_PROJECT_VERSION}</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
</plist>
#import <Foundation/Foundation.h>
@interface PodsDummy_AFJSONRPCClient : NSObject
@end
@implementation PodsDummy_AFJSONRPCClient
@end
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "AFJSONRPCClient.h"
FOUNDATION_EXPORT double AFJSONRPCClientVersionNumber;
FOUNDATION_EXPORT const unsigned char AFJSONRPCClientVersionString[];
framework module AFJSONRPCClient {
umbrella header "AFJSONRPCClient-umbrella.h"
export *
module * { export * }
}
CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/AFJSONRPCClient
FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking"
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
PODS_BUILD_DIR = ${BUILD_DIR}
PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
PODS_ROOT = ${SRCROOT}
PODS_TARGET_SRCROOT = ${PODS_ROOT}/AFJSONRPCClient
PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier}
SKIP_INSTALL = YES
USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key> <key>CFBundlePackageType</key>
<string>FMWK</string> <string>FMWK</string>
<key>CFBundleShortVersionString</key> <key>CFBundleShortVersionString</key>
<string>3.2.1</string> <string>2.7.0</string>
<key>CFBundleSignature</key> <key>CFBundleSignature</key>
<string>????</string> <string>????</string>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>
......
...@@ -17,7 +17,3 @@ ...@@ -17,7 +17,3 @@
#ifndef TARGET_OS_WATCH #ifndef TARGET_OS_WATCH
#define TARGET_OS_WATCH 0 #define TARGET_OS_WATCH 0
#endif #endif
#ifndef TARGET_OS_TV
#define TARGET_OS_TV 0
#endif
...@@ -11,17 +11,18 @@ ...@@ -11,17 +11,18 @@
#endif #endif
#import "AFNetworking.h" #import "AFNetworking.h"
#import "AFURLConnectionOperation.h"
#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFHTTPSessionManager.h" #import "AFHTTPSessionManager.h"
#import "AFURLSessionManager.h" #import "AFURLSessionManager.h"
#import "AFCompatibilityMacros.h"
#import "AFNetworkReachabilityManager.h" #import "AFNetworkReachabilityManager.h"
#import "AFSecurityPolicy.h" #import "AFSecurityPolicy.h"
#import "AFURLRequestSerialization.h" #import "AFURLRequestSerialization.h"
#import "AFURLResponseSerialization.h" #import "AFURLResponseSerialization.h"
#import "AFAutoPurgingImageCache.h"
#import "AFImageDownloader.h"
#import "AFNetworkActivityIndicatorManager.h" #import "AFNetworkActivityIndicatorManager.h"
#import "UIActivityIndicatorView+AFNetworking.h" #import "UIActivityIndicatorView+AFNetworking.h"
#import "UIAlertView+AFNetworking.h"
#import "UIButton+AFNetworking.h" #import "UIButton+AFNetworking.h"
#import "UIImage+AFNetworking.h" #import "UIImage+AFNetworking.h"
#import "UIImageView+AFNetworking.h" #import "UIImageView+AFNetworking.h"
......
# Acknowledgements # Acknowledgements
This application makes use of the following third party libraries: This application makes use of the following third party libraries:
## AFJSONRPCClient
Copyright (c) 2013 JustCommunication
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.
## AFNetworking ## AFNetworking
Copyright (c) 2011-2016 Alamofire Software Foundation (http://alamofire.org/) Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
......
...@@ -14,7 +14,36 @@ ...@@ -14,7 +14,36 @@
</dict> </dict>
<dict> <dict>
<key>FooterText</key> <key>FooterText</key>
<string>Copyright (c) 2011-2016 Alamofire Software Foundation (http://alamofire.org/) <string>Copyright (c) 2013 JustCommunication
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.
</string>
<key>License</key>
<string>MIT</string>
<key>Title</key>
<string>AFJSONRPCClient</string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>FooterText</key>
<string>Copyright (c) 20112015 Alamofire Software Foundation (http://alamofire.org/)
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
......
${PODS_ROOT}/Target Support Files/Pods-MutiFaceDemo/Pods-MutiFaceDemo-frameworks.sh ${PODS_ROOT}/Target Support Files/Pods-MutiFaceDemo/Pods-MutiFaceDemo-frameworks.sh
${BUILT_PRODUCTS_DIR}/AFJSONRPCClient/AFJSONRPCClient.framework
${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework ${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework
${BUILT_PRODUCTS_DIR}/IQKeyboardManager/IQKeyboardManager.framework ${BUILT_PRODUCTS_DIR}/IQKeyboardManager/IQKeyboardManager.framework
${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework ${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework
\ No newline at end of file
${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AFJSONRPCClient.framework
${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AFNetworking.framework ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AFNetworking.framework
${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/IQKeyboardManager.framework ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/IQKeyboardManager.framework
${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Masonry.framework ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Masonry.framework
\ No newline at end of file
${PODS_ROOT}/Target Support Files/Pods-MutiFaceDemo/Pods-MutiFaceDemo-frameworks.sh ${PODS_ROOT}/Target Support Files/Pods-MutiFaceDemo/Pods-MutiFaceDemo-frameworks.sh
${BUILT_PRODUCTS_DIR}/AFJSONRPCClient/AFJSONRPCClient.framework
${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework ${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework
${BUILT_PRODUCTS_DIR}/IQKeyboardManager/IQKeyboardManager.framework ${BUILT_PRODUCTS_DIR}/IQKeyboardManager/IQKeyboardManager.framework
${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework ${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework
\ No newline at end of file
${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AFJSONRPCClient.framework
${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AFNetworking.framework ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AFNetworking.framework
${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/IQKeyboardManager.framework ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/IQKeyboardManager.framework
${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Masonry.framework ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Masonry.framework
\ No newline at end of file
...@@ -161,11 +161,13 @@ strip_invalid_archs() { ...@@ -161,11 +161,13 @@ strip_invalid_archs() {
if [[ "$CONFIGURATION" == "Debug" ]]; then if [[ "$CONFIGURATION" == "Debug" ]]; then
install_framework "${BUILT_PRODUCTS_DIR}/AFJSONRPCClient/AFJSONRPCClient.framework"
install_framework "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework" install_framework "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework"
install_framework "${BUILT_PRODUCTS_DIR}/IQKeyboardManager/IQKeyboardManager.framework" install_framework "${BUILT_PRODUCTS_DIR}/IQKeyboardManager/IQKeyboardManager.framework"
install_framework "${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework" install_framework "${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework"
fi fi
if [[ "$CONFIGURATION" == "Release" ]]; then if [[ "$CONFIGURATION" == "Release" ]]; then
install_framework "${BUILT_PRODUCTS_DIR}/AFJSONRPCClient/AFJSONRPCClient.framework"
install_framework "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework" install_framework "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework"
install_framework "${BUILT_PRODUCTS_DIR}/IQKeyboardManager/IQKeyboardManager.framework" install_framework "${BUILT_PRODUCTS_DIR}/IQKeyboardManager/IQKeyboardManager.framework"
install_framework "${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework" install_framework "${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework"
......
FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking" "${PODS_CONFIGURATION_BUILD_DIR}/IQKeyboardManager" "${PODS_CONFIGURATION_BUILD_DIR}/Masonry" FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFJSONRPCClient" "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking" "${PODS_CONFIGURATION_BUILD_DIR}/IQKeyboardManager" "${PODS_CONFIGURATION_BUILD_DIR}/Masonry"
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking/AFNetworking.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/IQKeyboardManager/IQKeyboardManager.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Masonry/Masonry.framework/Headers" HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFJSONRPCClient/AFJSONRPCClient.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking/AFNetworking.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/IQKeyboardManager/IQKeyboardManager.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Masonry/Masonry.framework/Headers"
LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks'
OTHER_LDFLAGS = $(inherited) -framework "AFNetworking" -framework "CoreGraphics" -framework "Foundation" -framework "IQKeyboardManager" -framework "Masonry" -framework "MobileCoreServices" -framework "QuartzCore" -framework "Security" -framework "SystemConfiguration" -framework "UIKit" OTHER_LDFLAGS = $(inherited) -framework "AFJSONRPCClient" -framework "AFNetworking" -framework "CoreGraphics" -framework "Foundation" -framework "IQKeyboardManager" -framework "Masonry" -framework "MobileCoreServices" -framework "QuartzCore" -framework "Security" -framework "SystemConfiguration" -framework "UIKit"
PODS_BUILD_DIR = ${BUILD_DIR} PODS_BUILD_DIR = ${BUILD_DIR}
PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
PODS_PODFILE_DIR_PATH = ${SRCROOT}/. PODS_PODFILE_DIR_PATH = ${SRCROOT}/.
......
FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking" "${PODS_CONFIGURATION_BUILD_DIR}/IQKeyboardManager" "${PODS_CONFIGURATION_BUILD_DIR}/Masonry" FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFJSONRPCClient" "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking" "${PODS_CONFIGURATION_BUILD_DIR}/IQKeyboardManager" "${PODS_CONFIGURATION_BUILD_DIR}/Masonry"
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking/AFNetworking.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/IQKeyboardManager/IQKeyboardManager.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Masonry/Masonry.framework/Headers" HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFJSONRPCClient/AFJSONRPCClient.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking/AFNetworking.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/IQKeyboardManager/IQKeyboardManager.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Masonry/Masonry.framework/Headers"
LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks'
OTHER_LDFLAGS = $(inherited) -framework "AFNetworking" -framework "CoreGraphics" -framework "Foundation" -framework "IQKeyboardManager" -framework "Masonry" -framework "MobileCoreServices" -framework "QuartzCore" -framework "Security" -framework "SystemConfiguration" -framework "UIKit" OTHER_LDFLAGS = $(inherited) -framework "AFJSONRPCClient" -framework "AFNetworking" -framework "CoreGraphics" -framework "Foundation" -framework "IQKeyboardManager" -framework "Masonry" -framework "MobileCoreServices" -framework "QuartzCore" -framework "Security" -framework "SystemConfiguration" -framework "UIKit"
PODS_BUILD_DIR = ${BUILD_DIR} PODS_BUILD_DIR = ${BUILD_DIR}
PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
PODS_PODFILE_DIR_PATH = ${SRCROOT}/. PODS_PODFILE_DIR_PATH = ${SRCROOT}/.
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册登录 后发表评论