mirror of
https://bitbucket.org/vendoo/vendoo_v1.0.git
synced 2025-12-25 03:37:39 +00:00
Ebay Listing Now Posts both information and single image
need to rework on categories since subcategory workflow added some complications, but that will be taken care of in a bug fix task
This commit is contained in:
parent
544a7baa87
commit
031a354996
10
Podfile
10
Podfile
@ -6,11 +6,13 @@ target 'Vendoo' do
|
||||
use_frameworks!
|
||||
|
||||
# Pods for Vendoo
|
||||
pod 'Firebase', '>= 2.5.0'
|
||||
pod 'PicoKit'
|
||||
pod 'AeroGearHttp'
|
||||
pod 'AeroGearOAuth2'
|
||||
pod 'Firebase'
|
||||
pod 'FirebaseAuth'
|
||||
pod 'Firebase/Database'
|
||||
pod 'Locksmith'
|
||||
# pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git'
|
||||
pod 'Alamofire-SwiftyJSON'
|
||||
pod 'OAuthSwift', '~> 0.5.0'
|
||||
pod 'FBSDKCoreKit'
|
||||
@ -24,13 +26,13 @@ use_frameworks!
|
||||
|
||||
|
||||
target 'VendooTests' do
|
||||
inherit! :search_paths
|
||||
# inherit! :search_paths
|
||||
# Pods for testing
|
||||
|
||||
end
|
||||
|
||||
target 'VendooUITests' do
|
||||
inherit! :search_paths
|
||||
# inherit! :search_paths
|
||||
# Pods for testing
|
||||
end
|
||||
|
||||
|
||||
50
Podfile.lock
50
Podfile.lock
@ -1,4 +1,28 @@
|
||||
PODS:
|
||||
- AeroGearHttp (0.6.0)
|
||||
- AeroGearOAuth2 (0.5.1):
|
||||
- AeroGearHttp
|
||||
- AFNetworking (2.6.3):
|
||||
- AFNetworking/NSURLConnection (= 2.6.3)
|
||||
- AFNetworking/NSURLSession (= 2.6.3)
|
||||
- AFNetworking/Reachability (= 2.6.3)
|
||||
- AFNetworking/Security (= 2.6.3)
|
||||
- AFNetworking/Serialization (= 2.6.3)
|
||||
- AFNetworking/UIKit (= 2.6.3)
|
||||
- AFNetworking/NSURLConnection (2.6.3):
|
||||
- AFNetworking/Reachability
|
||||
- AFNetworking/Security
|
||||
- AFNetworking/Serialization
|
||||
- AFNetworking/NSURLSession (2.6.3):
|
||||
- AFNetworking/Reachability
|
||||
- AFNetworking/Security
|
||||
- AFNetworking/Serialization
|
||||
- AFNetworking/Reachability (2.6.3)
|
||||
- AFNetworking/Security (2.6.3)
|
||||
- AFNetworking/Serialization (2.6.3)
|
||||
- AFNetworking/UIKit (2.6.3):
|
||||
- AFNetworking/NSURLConnection
|
||||
- AFNetworking/NSURLSession
|
||||
- Alamofire (3.4.1)
|
||||
- Alamofire-SwiftyJSON (0.1.1):
|
||||
- Alamofire (~> 3.4)
|
||||
@ -47,6 +71,7 @@ PODS:
|
||||
- FirebaseStorage (1.0.2):
|
||||
- FirebaseAnalytics (~> 3.2)
|
||||
- GoogleNetworkingUtilities (~> 1.2)
|
||||
- GDataXML-HTML (1.3.0)
|
||||
- GoogleInterchangeUtilities (1.2.1):
|
||||
- GoogleSymbolUtilities (~> 1.0)
|
||||
- GoogleNetworkingUtilities (1.2.1):
|
||||
@ -59,27 +84,46 @@ PODS:
|
||||
- GoogleSymbolUtilities (~> 1.0)
|
||||
- Locksmith (2.0.8)
|
||||
- OAuthSwift (0.5.2)
|
||||
- PicoKit (0.7.2):
|
||||
- PicoKit/WebService (= 0.7.2)
|
||||
- PicoKit/Core (0.7.2):
|
||||
- GDataXML-HTML (~> 1.3.0)
|
||||
- PicoKit/OrderedDictionary
|
||||
- PicoKit/XMLWriter
|
||||
- PicoKit/OrderedDictionary (0.7.2)
|
||||
- PicoKit/Soap (0.7.2):
|
||||
- PicoKit/Core
|
||||
- PicoKit/WebService (0.7.2):
|
||||
- AFNetworking (~> 2.6.0)
|
||||
- PicoKit/Soap
|
||||
- PicoKit/XMLWriter (0.7.2)
|
||||
- SwiftyJSON (2.3.2)
|
||||
- SWRevealViewController (2.3.0)
|
||||
- TYMActivityIndicatorView (0.3.3)
|
||||
- UIImageViewModeScaleAspect (1.5)
|
||||
|
||||
DEPENDENCIES:
|
||||
- AeroGearHttp
|
||||
- AeroGearOAuth2
|
||||
- Alamofire-SwiftyJSON
|
||||
- BSImagePicker (~> 2.3)
|
||||
- FBSDKCoreKit
|
||||
- FBSDKLoginKit
|
||||
- FBSDKShareKit
|
||||
- Firebase (>= 2.5.0)
|
||||
- Firebase
|
||||
- Firebase/Database
|
||||
- Firebase/Storage
|
||||
- FirebaseAuth
|
||||
- Locksmith
|
||||
- OAuthSwift (~> 0.5.0)
|
||||
- PicoKit
|
||||
- SWRevealViewController
|
||||
- TYMActivityIndicatorView
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
AeroGearHttp: e958f301cc2d1c7fbfd4b61af187ea3490040a48
|
||||
AeroGearOAuth2: 6f29d3fac8b78a0ff6d51b04c4ba1a02baed2e52
|
||||
AFNetworking: cb8d14a848e831097108418f5d49217339d4eb60
|
||||
Alamofire: 01a82e2f6c0f860ade35534c8dd88be61bdef40c
|
||||
Alamofire-SwiftyJSON: 5812bb37accc36897cc2f2dabb070d8ebcd7ac98
|
||||
Bolts: 8a7995239dbe724f9cba2248b766d48b7ebdd322
|
||||
@ -94,6 +138,7 @@ SPEC CHECKSUMS:
|
||||
FirebaseDatabase: 59bea2e7dfd81b3b8b2f8e396caf1a52c2ced6f7
|
||||
FirebaseInstanceID: ba1e640935235e5fac39dfa816fe7660e72e1a8a
|
||||
FirebaseStorage: fa2a87dee81f682f553af6839daa37a750e65f6a
|
||||
GDataXML-HTML: 7adc03668cab35c288f1dbb8929a179f0fece898
|
||||
GoogleInterchangeUtilities: def8415a862effc67d549d5b5b0b9c7a2f97d4de
|
||||
GoogleNetworkingUtilities: 3e83269048cfb498dc7ec83ab36813360965c74f
|
||||
GoogleParsingUtilities: 30b3896f9ee167dc78747f013d3de157ced1cadf
|
||||
@ -101,11 +146,12 @@ SPEC CHECKSUMS:
|
||||
GoogleUtilities: 56c5ac05b7aa5dc417a1bb85221a9516e04d7032
|
||||
Locksmith: a8ed41ac4c06506ea8cb199d8ec8a8d3d108eb2a
|
||||
OAuthSwift: 1ef042d4362e755e24a78f158d817245641a5d24
|
||||
PicoKit: 9079bce659a8d5408c8af1c45254b971df614de3
|
||||
SwiftyJSON: 04ccea08915aa0109039157c7974cf0298da292a
|
||||
SWRevealViewController: 6d3fd97f70112fd7cef9de14df4260eacce4c63a
|
||||
TYMActivityIndicatorView: ad816387ebd5952c376af129218722733044148b
|
||||
UIImageViewModeScaleAspect: 11a790a0b9d248a13dc63e3a78991f1463b6d84e
|
||||
|
||||
PODFILE CHECKSUM: f0e94f082ecd182e6ea530edddd9bc1c1cb65997
|
||||
PODFILE CHECKSUM: 3b36a7c734809ee54f4ecf0055d9910a9279d555
|
||||
|
||||
COCOAPODS: 1.0.0
|
||||
|
||||
70
Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.h
generated
Normal file
70
Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.h
generated
Normal file
@ -0,0 +1,70 @@
|
||||
// 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 responseObject))success
|
||||
failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
206
Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m
generated
Normal file
206
Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m
generated
Normal file
@ -0,0 +1,206 @@
|
||||
// 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) 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 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
|
||||
326
Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.h
generated
Normal file
326
Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.h
generated
Normal file
@ -0,0 +1,326 @@
|
||||
// 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 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 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 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 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 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 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 responseObject))success
|
||||
failure:(nullable void (^)(AFHTTPRequestOperation * __nullable operation, NSError *error))failure;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
290
Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.m
generated
Normal file
290
Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.m
generated
Normal file
@ -0,0 +1,290 @@
|
||||
// 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 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 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 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 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 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 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 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 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
|
||||
253
Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h
generated
Normal file
253
Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h
generated
Normal file
@ -0,0 +1,253 @@
|
||||
// AFHTTPSessionManager.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>
|
||||
#if !TARGET_OS_WATCH
|
||||
#import <SystemConfiguration/SystemConfiguration.h>
|
||||
#endif
|
||||
#import <Availability.h>
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED
|
||||
#import <MobileCoreServices/MobileCoreServices.h>
|
||||
#else
|
||||
#import <CoreServices/CoreServices.h>
|
||||
#endif
|
||||
|
||||
#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.
|
||||
|
||||
## 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 data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:completionHandler:`.
|
||||
|
||||
## 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.
|
||||
|
||||
@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
|
||||
|
||||
@interface AFHTTPSessionManager : AFURLSessionManager <NSSecureCoding, NSCopying>
|
||||
|
||||
/**
|
||||
The URL used to 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 an instance of `AFJSONResponseSerializer`.
|
||||
|
||||
@warning `responseSerializer` must not be `nil`.
|
||||
*/
|
||||
@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
|
||||
|
||||
///---------------------
|
||||
/// @name Initialization
|
||||
///---------------------
|
||||
|
||||
/**
|
||||
Creates and returns an `AFHTTPSessionManager` object.
|
||||
*/
|
||||
+ (instancetype)manager;
|
||||
|
||||
/**
|
||||
Initializes an `AFHTTPSessionManager` object with the specified base URL.
|
||||
|
||||
@param url The base URL for the HTTP client.
|
||||
|
||||
@return The newly-initialized HTTP client
|
||||
*/
|
||||
- (instancetype)initWithBaseURL:(nullable NSURL *)url;
|
||||
|
||||
/**
|
||||
Initializes an `AFHTTPSessionManager` object with the specified base URL.
|
||||
|
||||
This is the designated initializer.
|
||||
|
||||
@param url The base URL for the HTTP client.
|
||||
@param configuration The configuration used to create the managed session.
|
||||
|
||||
@return The newly-initialized HTTP client
|
||||
*/
|
||||
- (instancetype)initWithBaseURL:(nullable NSURL *)url
|
||||
sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
|
||||
|
||||
///---------------------------
|
||||
/// @name Making HTTP Requests
|
||||
///---------------------------
|
||||
|
||||
/**
|
||||
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 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:completionHandler:
|
||||
*/
|
||||
- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Creates and runs an `NSURLSessionDataTask` 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 task finishes successfully. This block has no return value and takes a single arguments: the data task.
|
||||
@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:completionHandler:
|
||||
*/
|
||||
- (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task))success
|
||||
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 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:completionHandler:
|
||||
*/
|
||||
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
|
||||
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 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:completionHandler:
|
||||
*/
|
||||
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Creates and runs an `NSURLSessionDataTask` 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 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:completionHandler:
|
||||
*/
|
||||
- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Creates and runs an `NSURLSessionDataTask` 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 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:completionHandler:
|
||||
*/
|
||||
- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Creates and runs an `NSURLSessionDataTask` 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 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:completionHandler:
|
||||
*/
|
||||
- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
328
Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m
generated
Normal file
328
Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m
generated
Normal file
@ -0,0 +1,328 @@
|
||||
// AFHTTPSessionManager.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 "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 "AFURLResponseSerialization.h"
|
||||
|
||||
#import <Availability.h>
|
||||
#import <Security/Security.h>
|
||||
|
||||
#ifdef _SYSTEMCONFIGURATION_H
|
||||
#import <netinet/in.h>
|
||||
#import <netinet6/in6.h>
|
||||
#import <arpa/inet.h>
|
||||
#import <ifaddrs.h>
|
||||
#import <netdb.h>
|
||||
#endif
|
||||
|
||||
#if TARGET_OS_IOS
|
||||
#import <UIKit/UIKit.h>
|
||||
#elif TARGET_OS_WATCH
|
||||
#import <WatchKit/WatchKit.h>
|
||||
#endif
|
||||
|
||||
@interface AFHTTPSessionManager ()
|
||||
@property (readwrite, nonatomic, strong) NSURL *baseURL;
|
||||
@end
|
||||
|
||||
@implementation AFHTTPSessionManager
|
||||
@dynamic responseSerializer;
|
||||
|
||||
+ (instancetype)manager {
|
||||
return [[[self class] alloc] initWithBaseURL:nil];
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
return [self initWithBaseURL:nil];
|
||||
}
|
||||
|
||||
- (instancetype)initWithBaseURL:(NSURL *)url {
|
||||
return [self initWithBaseURL:url sessionConfiguration:nil];
|
||||
}
|
||||
|
||||
- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
|
||||
return [self initWithBaseURL:nil sessionConfiguration:configuration];
|
||||
}
|
||||
|
||||
- (instancetype)initWithBaseURL:(NSURL *)url
|
||||
sessionConfiguration:(NSURLSessionConfiguration *)configuration
|
||||
{
|
||||
self = [super initWithSessionConfiguration:configuration];
|
||||
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];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
#ifdef _SYSTEMCONFIGURATION_H
|
||||
#endif
|
||||
|
||||
- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
|
||||
NSParameterAssert(requestSerializer);
|
||||
|
||||
_requestSerializer = requestSerializer;
|
||||
}
|
||||
|
||||
- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
|
||||
NSParameterAssert(responseSerializer);
|
||||
|
||||
[super setResponseSerializer:responseSerializer];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (NSURLSessionDataTask *)GET:(NSString *)URLString
|
||||
parameters:(id)parameters
|
||||
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
|
||||
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
|
||||
{
|
||||
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" URLString:URLString parameters:parameters success:success failure:failure];
|
||||
|
||||
[dataTask resume];
|
||||
|
||||
return dataTask;
|
||||
}
|
||||
|
||||
- (NSURLSessionDataTask *)HEAD:(NSString *)URLString
|
||||
parameters:(id)parameters
|
||||
success:(void (^)(NSURLSessionDataTask *task))success
|
||||
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
|
||||
{
|
||||
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters success:^(NSURLSessionDataTask *task, __unused id responseObject) {
|
||||
if (success) {
|
||||
success(task);
|
||||
}
|
||||
} failure:failure];
|
||||
|
||||
[dataTask resume];
|
||||
|
||||
return dataTask;
|
||||
}
|
||||
|
||||
- (NSURLSessionDataTask *)POST:(NSString *)URLString
|
||||
parameters:(id)parameters
|
||||
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
|
||||
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
|
||||
{
|
||||
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters success:success failure:failure];
|
||||
|
||||
[dataTask resume];
|
||||
|
||||
return dataTask;
|
||||
}
|
||||
|
||||
- (NSURLSessionDataTask *)POST:(NSString *)URLString
|
||||
parameters:(id)parameters
|
||||
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
|
||||
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
|
||||
failure:(void (^)(NSURLSessionDataTask *task, 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;
|
||||
}
|
||||
|
||||
__block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
|
||||
if (error) {
|
||||
if (failure) {
|
||||
failure(task, error);
|
||||
}
|
||||
} else {
|
||||
if (success) {
|
||||
success(task, responseObject);
|
||||
}
|
||||
}
|
||||
}];
|
||||
|
||||
[task resume];
|
||||
|
||||
return task;
|
||||
}
|
||||
|
||||
- (NSURLSessionDataTask *)PUT:(NSString *)URLString
|
||||
parameters:(id)parameters
|
||||
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
|
||||
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
|
||||
{
|
||||
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters success:success failure:failure];
|
||||
|
||||
[dataTask resume];
|
||||
|
||||
return dataTask;
|
||||
}
|
||||
|
||||
- (NSURLSessionDataTask *)PATCH:(NSString *)URLString
|
||||
parameters:(id)parameters
|
||||
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
|
||||
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
|
||||
{
|
||||
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters success:success failure:failure];
|
||||
|
||||
[dataTask resume];
|
||||
|
||||
return dataTask;
|
||||
}
|
||||
|
||||
- (NSURLSessionDataTask *)DELETE:(NSString *)URLString
|
||||
parameters:(id)parameters
|
||||
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
|
||||
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
|
||||
{
|
||||
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters success:success failure:failure];
|
||||
|
||||
[dataTask resume];
|
||||
|
||||
return dataTask;
|
||||
}
|
||||
|
||||
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
|
||||
URLString:(NSString *)URLString
|
||||
parameters:(id)parameters
|
||||
success:(void (^)(NSURLSessionDataTask *, id))success
|
||||
failure:(void (^)(NSURLSessionDataTask *, NSError *))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;
|
||||
}
|
||||
|
||||
__block NSURLSessionDataTask *dataTask = nil;
|
||||
dataTask = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
|
||||
if (error) {
|
||||
if (failure) {
|
||||
failure(dataTask, error);
|
||||
}
|
||||
} else {
|
||||
if (success) {
|
||||
success(dataTask, responseObject);
|
||||
}
|
||||
}
|
||||
}];
|
||||
|
||||
return dataTask;
|
||||
}
|
||||
|
||||
#pragma mark - NSObject
|
||||
|
||||
- (NSString *)description {
|
||||
return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue];
|
||||
}
|
||||
|
||||
#pragma mark - NSSecureCoding
|
||||
|
||||
+ (BOOL)supportsSecureCoding {
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (id)initWithCoder:(NSCoder *)decoder {
|
||||
NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))];
|
||||
NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
|
||||
if (!configuration) {
|
||||
NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"];
|
||||
if (configurationIdentifier) {
|
||||
#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1100)
|
||||
configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier];
|
||||
#else
|
||||
configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier];
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
self = [self initWithBaseURL:baseURL sessionConfiguration:configuration];
|
||||
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 {
|
||||
[super encodeWithCoder:coder];
|
||||
|
||||
[coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))];
|
||||
if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) {
|
||||
[coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
|
||||
} else {
|
||||
[coder encodeObject:self.session.configuration.identifier forKey:@"identifier"];
|
||||
}
|
||||
[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 {
|
||||
AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration];
|
||||
|
||||
HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
|
||||
HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
|
||||
HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone];
|
||||
return HTTPClient;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
207
Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h
generated
Normal file
207
Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h
generated
Normal file
@ -0,0 +1,207 @@
|
||||
// AFNetworkReachabilityManager.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>
|
||||
|
||||
#if !TARGET_OS_WATCH
|
||||
#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) {
|
||||
AFNetworkReachabilityStatusUnknown = -1,
|
||||
AFNetworkReachabilityStatusNotReachable = 0,
|
||||
AFNetworkReachabilityStatusReachableViaWWAN = 1,
|
||||
AFNetworkReachabilityStatusReachableViaWiFi = 2,
|
||||
};
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
|
||||
|
||||
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/)
|
||||
|
||||
@warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
|
||||
*/
|
||||
@interface AFNetworkReachabilityManager : NSObject
|
||||
|
||||
/**
|
||||
The current network reachability status.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
|
||||
|
||||
/**
|
||||
Whether or not the network is currently reachable.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable;
|
||||
|
||||
/**
|
||||
Whether or not the network is currently reachable via WWAN.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN;
|
||||
|
||||
/**
|
||||
Whether or not the network is currently reachable via WiFi.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi;
|
||||
|
||||
///---------------------
|
||||
/// @name Initialization
|
||||
///---------------------
|
||||
|
||||
/**
|
||||
Returns the shared network reachability manager.
|
||||
*/
|
||||
+ (instancetype)sharedManager;
|
||||
|
||||
/**
|
||||
Creates and returns a network reachability manager for the specified domain.
|
||||
|
||||
@param domain The domain used to evaluate network reachability.
|
||||
|
||||
@return An initialized network reachability manager, actively monitoring the specified domain.
|
||||
*/
|
||||
+ (instancetype)managerForDomain:(NSString *)domain;
|
||||
|
||||
/**
|
||||
Creates and returns a network reachability manager for the socket address.
|
||||
|
||||
@param address The socket address (`sockaddr_in`) used to evaluate network reachability.
|
||||
|
||||
@return An initialized network reachability manager, actively monitoring the specified socket address.
|
||||
*/
|
||||
+ (instancetype)managerForAddress:(const void *)address;
|
||||
|
||||
/**
|
||||
Initializes an instance of a network reachability manager from the specified reachability object.
|
||||
|
||||
@param reachability The reachability object to monitor.
|
||||
|
||||
@return An initialized network reachability manager, actively monitoring the specified reachability.
|
||||
*/
|
||||
- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER;
|
||||
|
||||
///--------------------------------------------------
|
||||
/// @name Starting & Stopping Reachability Monitoring
|
||||
///--------------------------------------------------
|
||||
|
||||
/**
|
||||
Starts monitoring for changes in network reachability status.
|
||||
*/
|
||||
- (void)startMonitoring;
|
||||
|
||||
/**
|
||||
Stops monitoring for changes in network reachability status.
|
||||
*/
|
||||
- (void)stopMonitoring;
|
||||
|
||||
///-------------------------------------------------
|
||||
/// @name Getting Localized Reachability Description
|
||||
///-------------------------------------------------
|
||||
|
||||
/**
|
||||
Returns a localized string representation of the current network reachability status.
|
||||
*/
|
||||
- (NSString *)localizedNetworkReachabilityStatusString;
|
||||
|
||||
///---------------------------------------------------
|
||||
/// @name Setting Network Reachability Change Callback
|
||||
///---------------------------------------------------
|
||||
|
||||
/**
|
||||
Sets a callback to be executed when the network availability of the `baseURL` host changes.
|
||||
|
||||
@param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
|
||||
*/
|
||||
- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block;
|
||||
|
||||
@end
|
||||
|
||||
///----------------
|
||||
/// @name Constants
|
||||
///----------------
|
||||
|
||||
/**
|
||||
## Network Reachability
|
||||
|
||||
The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses.
|
||||
|
||||
enum {
|
||||
AFNetworkReachabilityStatusUnknown,
|
||||
AFNetworkReachabilityStatusNotReachable,
|
||||
AFNetworkReachabilityStatusReachableViaWWAN,
|
||||
AFNetworkReachabilityStatusReachableViaWiFi,
|
||||
}
|
||||
|
||||
`AFNetworkReachabilityStatusUnknown`
|
||||
The `baseURL` host reachability is not known.
|
||||
|
||||
`AFNetworkReachabilityStatusNotReachable`
|
||||
The `baseURL` host cannot be reached.
|
||||
|
||||
`AFNetworkReachabilityStatusReachableViaWWAN`
|
||||
The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
|
||||
|
||||
`AFNetworkReachabilityStatusReachableViaWiFi`
|
||||
The `baseURL` host can be reached via a Wi-Fi connection.
|
||||
|
||||
### Keys for Notification UserInfo Dictionary
|
||||
|
||||
Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
|
||||
|
||||
`AFNetworkingReachabilityNotificationStatusItem`
|
||||
A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
|
||||
The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
|
||||
*/
|
||||
|
||||
///--------------------
|
||||
/// @name Notifications
|
||||
///--------------------
|
||||
|
||||
/**
|
||||
Posted when network reachability changes.
|
||||
This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
|
||||
|
||||
@warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification;
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem;
|
||||
|
||||
///--------------------
|
||||
/// @name Functions
|
||||
///--------------------
|
||||
|
||||
/**
|
||||
Returns a localized string representation of an `AFNetworkReachabilityStatus` value.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status);
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
#endif
|
||||
248
Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m
generated
Normal file
248
Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m
generated
Normal file
@ -0,0 +1,248 @@
|
||||
// AFNetworkReachabilityManager.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 "AFNetworkReachabilityManager.h"
|
||||
#if !TARGET_OS_WATCH
|
||||
|
||||
#import <netinet/in.h>
|
||||
#import <netinet6/in6.h>
|
||||
#import <arpa/inet.h>
|
||||
#import <ifaddrs.h>
|
||||
#import <netdb.h>
|
||||
|
||||
NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
|
||||
NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem";
|
||||
|
||||
typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status);
|
||||
|
||||
NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) {
|
||||
switch (status) {
|
||||
case AFNetworkReachabilityStatusNotReachable:
|
||||
return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil);
|
||||
case AFNetworkReachabilityStatusReachableViaWWAN:
|
||||
return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil);
|
||||
case AFNetworkReachabilityStatusReachableViaWiFi:
|
||||
return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil);
|
||||
case AFNetworkReachabilityStatusUnknown:
|
||||
default:
|
||||
return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil);
|
||||
}
|
||||
}
|
||||
|
||||
static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
|
||||
BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
|
||||
BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
|
||||
BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0));
|
||||
BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0);
|
||||
BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction));
|
||||
|
||||
AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
|
||||
if (isNetworkReachable == NO) {
|
||||
status = AFNetworkReachabilityStatusNotReachable;
|
||||
}
|
||||
#if TARGET_OS_IPHONE
|
||||
else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) {
|
||||
status = AFNetworkReachabilityStatusReachableViaWWAN;
|
||||
}
|
||||
#endif
|
||||
else {
|
||||
status = AFNetworkReachabilityStatusReachableViaWiFi;
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue a status change notification for the main thread.
|
||||
*
|
||||
* This is done to ensure that the notifications are received in the same order
|
||||
* as they are sent. If notifications are sent directly, it is possible that
|
||||
* a queued notification (for an earlier status condition) is processed after
|
||||
* the later update, resulting in the listener being left in the wrong state.
|
||||
*/
|
||||
static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusBlock block) {
|
||||
AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (block) {
|
||||
block(status);
|
||||
}
|
||||
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
|
||||
NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) };
|
||||
[notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo];
|
||||
});
|
||||
}
|
||||
|
||||
static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
|
||||
AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusBlock)info);
|
||||
}
|
||||
|
||||
static const void * AFNetworkReachabilityRetainCallback(const void *info) {
|
||||
return Block_copy(info);
|
||||
}
|
||||
|
||||
static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||
if (info) {
|
||||
Block_release(info);
|
||||
}
|
||||
}
|
||||
|
||||
@interface AFNetworkReachabilityManager ()
|
||||
@property (readwrite, nonatomic, strong) id networkReachability;
|
||||
@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
|
||||
@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
|
||||
@end
|
||||
|
||||
@implementation AFNetworkReachabilityManager
|
||||
|
||||
+ (instancetype)sharedManager {
|
||||
static AFNetworkReachabilityManager *_sharedManager = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
struct sockaddr_in address;
|
||||
bzero(&address, sizeof(address));
|
||||
address.sin_len = sizeof(address);
|
||||
address.sin_family = AF_INET;
|
||||
|
||||
_sharedManager = [self managerForAddress:&address];
|
||||
});
|
||||
|
||||
return _sharedManager;
|
||||
}
|
||||
|
||||
#ifndef __clang_analyzer__
|
||||
+ (instancetype)managerForDomain:(NSString *)domain {
|
||||
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]);
|
||||
|
||||
AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
|
||||
|
||||
return manager;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef __clang_analyzer__
|
||||
+ (instancetype)managerForAddress:(const void *)address {
|
||||
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address);
|
||||
AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
|
||||
|
||||
return manager;
|
||||
}
|
||||
#endif
|
||||
|
||||
- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.networkReachability = CFBridgingRelease(reachability);
|
||||
self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (instancetype)init NS_UNAVAILABLE
|
||||
{
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
[self stopMonitoring];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (BOOL)isReachable {
|
||||
return [self isReachableViaWWAN] || [self isReachableViaWiFi];
|
||||
}
|
||||
|
||||
- (BOOL)isReachableViaWWAN {
|
||||
return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN;
|
||||
}
|
||||
|
||||
- (BOOL)isReachableViaWiFi {
|
||||
return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi;
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)startMonitoring {
|
||||
[self stopMonitoring];
|
||||
|
||||
if (!self.networkReachability) {
|
||||
return;
|
||||
}
|
||||
|
||||
__weak __typeof(self)weakSelf = self;
|
||||
AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {
|
||||
__strong __typeof(weakSelf)strongSelf = weakSelf;
|
||||
|
||||
strongSelf.networkReachabilityStatus = status;
|
||||
if (strongSelf.networkReachabilityStatusBlock) {
|
||||
strongSelf.networkReachabilityStatusBlock(status);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
id networkReachability = self.networkReachability;
|
||||
SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
|
||||
SCNetworkReachabilitySetCallback((__bridge SCNetworkReachabilityRef)networkReachability, AFNetworkReachabilityCallback, &context);
|
||||
SCNetworkReachabilityScheduleWithRunLoop((__bridge SCNetworkReachabilityRef)networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
|
||||
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
|
||||
SCNetworkReachabilityFlags flags;
|
||||
if (SCNetworkReachabilityGetFlags((__bridge SCNetworkReachabilityRef)networkReachability, &flags)) {
|
||||
AFPostReachabilityStatusChange(flags, callback);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)stopMonitoring {
|
||||
if (!self.networkReachability) {
|
||||
return;
|
||||
}
|
||||
|
||||
SCNetworkReachabilityUnscheduleFromRunLoop((__bridge SCNetworkReachabilityRef)self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (NSString *)localizedNetworkReachabilityStatusString {
|
||||
return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus);
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block {
|
||||
self.networkReachabilityStatusBlock = block;
|
||||
}
|
||||
|
||||
#pragma mark - NSKeyValueObserving
|
||||
|
||||
+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
|
||||
if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) {
|
||||
return [NSSet setWithObject:@"networkReachabilityStatus"];
|
||||
}
|
||||
|
||||
return [super keyPathsForValuesAffectingValueForKey:key];
|
||||
}
|
||||
|
||||
@end
|
||||
#endif
|
||||
46
Pods/AFNetworking/AFNetworking/AFNetworking.h
generated
Normal file
46
Pods/AFNetworking/AFNetworking/AFNetworking.h
generated
Normal file
@ -0,0 +1,46 @@
|
||||
// AFNetworking.h
|
||||
//
|
||||
// Copyright (c) 2013 AFNetworking (http://afnetworking.com/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <Availability.h>
|
||||
|
||||
#ifndef _AFNETWORKING_
|
||||
#define _AFNETWORKING_
|
||||
|
||||
#import "AFURLRequestSerialization.h"
|
||||
#import "AFURLResponseSerialization.h"
|
||||
#import "AFSecurityPolicy.h"
|
||||
#if !TARGET_OS_WATCH
|
||||
#import "AFNetworkReachabilityManager.h"
|
||||
#import "AFURLConnectionOperation.h"
|
||||
#import "AFHTTPRequestOperation.h"
|
||||
#import "AFHTTPRequestOperationManager.h"
|
||||
#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 "AFHTTPSessionManager.h"
|
||||
#endif
|
||||
|
||||
#endif /* _AFNETWORKING_ */
|
||||
142
Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h
generated
Normal file
142
Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h
generated
Normal file
@ -0,0 +1,142 @@
|
||||
// AFSecurityPolicy.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 <Security/Security.h>
|
||||
|
||||
typedef NS_ENUM(NSUInteger, AFSSLPinningMode) {
|
||||
AFSSLPinningModeNone,
|
||||
AFSSLPinningModePublicKey,
|
||||
AFSSLPinningModeCertificate,
|
||||
};
|
||||
|
||||
/**
|
||||
`AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
|
||||
|
||||
Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
|
||||
*/
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface AFSecurityPolicy : NSObject <NSSecureCoding, NSCopying>
|
||||
|
||||
/**
|
||||
The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
|
||||
|
||||
/**
|
||||
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.
|
||||
*/
|
||||
@property (nonatomic, strong, nullable) NSArray *pinnedCertificates;
|
||||
|
||||
/**
|
||||
Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`.
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL allowInvalidCertificates;
|
||||
|
||||
/**
|
||||
Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`.
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL validatesDomainName;
|
||||
|
||||
///-----------------------------------------
|
||||
/// @name Getting Specific Security Policies
|
||||
///-----------------------------------------
|
||||
|
||||
/**
|
||||
Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys.
|
||||
|
||||
@return The default security policy.
|
||||
*/
|
||||
+ (instancetype)defaultPolicy;
|
||||
|
||||
///---------------------
|
||||
/// @name Initialization
|
||||
///---------------------
|
||||
|
||||
/**
|
||||
Creates and returns a security policy with the specified pinning mode.
|
||||
|
||||
@param pinningMode The SSL pinning mode.
|
||||
|
||||
@return A new security policy.
|
||||
*/
|
||||
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode;
|
||||
|
||||
///------------------------------
|
||||
/// @name Evaluating Server Trust
|
||||
///------------------------------
|
||||
|
||||
/**
|
||||
Whether or not the specified server trust should be accepted, based on the security policy.
|
||||
|
||||
This method should be used when responding to an authentication challenge from a server.
|
||||
|
||||
@param serverTrust The X.509 certificate trust of the server.
|
||||
|
||||
@return Whether or not to trust the server.
|
||||
|
||||
@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.
|
||||
|
||||
This method should be used when responding to an authentication challenge from a server.
|
||||
|
||||
@param serverTrust The X.509 certificate trust of the server.
|
||||
@param domain The domain of serverTrust. If `nil`, the domain will not be validated.
|
||||
|
||||
@return Whether or not to trust the server.
|
||||
*/
|
||||
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
|
||||
forDomain:(nullable NSString *)domain;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
///----------------
|
||||
/// @name Constants
|
||||
///----------------
|
||||
|
||||
/**
|
||||
## SSL Pinning Modes
|
||||
|
||||
The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes.
|
||||
|
||||
enum {
|
||||
AFSSLPinningModeNone,
|
||||
AFSSLPinningModePublicKey,
|
||||
AFSSLPinningModeCertificate,
|
||||
}
|
||||
|
||||
`AFSSLPinningModeNone`
|
||||
Do not used pinned certificates to validate servers.
|
||||
|
||||
`AFSSLPinningModePublicKey`
|
||||
Validate host certificates against public keys of pinned certificates.
|
||||
|
||||
`AFSSLPinningModeCertificate`
|
||||
Validate host certificates against pinned certificates.
|
||||
*/
|
||||
347
Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m
generated
Normal file
347
Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m
generated
Normal file
@ -0,0 +1,347 @@
|
||||
// AFSecurityPolicy.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 "AFSecurityPolicy.h"
|
||||
|
||||
#import <AssertMacros.h>
|
||||
|
||||
#if !TARGET_OS_IOS && !TARGET_OS_WATCH
|
||||
static NSData * AFSecKeyGetData(SecKeyRef key) {
|
||||
CFDataRef data = NULL;
|
||||
|
||||
__Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out);
|
||||
|
||||
return (__bridge_transfer NSData *)data;
|
||||
|
||||
_out:
|
||||
if (data) {
|
||||
CFRelease(data);
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
#endif
|
||||
|
||||
static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
|
||||
#if TARGET_OS_IOS || TARGET_OS_WATCH
|
||||
return [(__bridge id)key1 isEqual:(__bridge id)key2];
|
||||
#else
|
||||
return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)];
|
||||
#endif
|
||||
}
|
||||
|
||||
static id AFPublicKeyForCertificate(NSData *certificate) {
|
||||
id allowedPublicKey = nil;
|
||||
SecCertificateRef allowedCertificate;
|
||||
SecCertificateRef allowedCertificates[1];
|
||||
CFArrayRef tempCertificates = nil;
|
||||
SecPolicyRef policy = nil;
|
||||
SecTrustRef allowedTrust = nil;
|
||||
SecTrustResultType result;
|
||||
|
||||
allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
|
||||
__Require_Quiet(allowedCertificate != NULL, _out);
|
||||
|
||||
allowedCertificates[0] = allowedCertificate;
|
||||
tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);
|
||||
|
||||
policy = SecPolicyCreateBasicX509();
|
||||
__Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out);
|
||||
__Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out);
|
||||
|
||||
allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);
|
||||
|
||||
_out:
|
||||
if (allowedTrust) {
|
||||
CFRelease(allowedTrust);
|
||||
}
|
||||
|
||||
if (policy) {
|
||||
CFRelease(policy);
|
||||
}
|
||||
|
||||
if (tempCertificates) {
|
||||
CFRelease(tempCertificates);
|
||||
}
|
||||
|
||||
if (allowedCertificate) {
|
||||
CFRelease(allowedCertificate);
|
||||
}
|
||||
|
||||
return allowedPublicKey;
|
||||
}
|
||||
|
||||
static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
|
||||
BOOL isValid = NO;
|
||||
SecTrustResultType result;
|
||||
__Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out);
|
||||
|
||||
isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
|
||||
|
||||
_out:
|
||||
return isValid;
|
||||
}
|
||||
|
||||
static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) {
|
||||
CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
|
||||
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
|
||||
|
||||
for (CFIndex i = 0; i < certificateCount; i++) {
|
||||
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
|
||||
[trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
|
||||
}
|
||||
|
||||
return [NSArray arrayWithArray:trustChain];
|
||||
}
|
||||
|
||||
static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
|
||||
SecPolicyRef policy = SecPolicyCreateBasicX509();
|
||||
CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
|
||||
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
|
||||
for (CFIndex i = 0; i < certificateCount; i++) {
|
||||
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
|
||||
|
||||
SecCertificateRef someCertificates[] = {certificate};
|
||||
CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
|
||||
|
||||
SecTrustRef trust;
|
||||
__Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out);
|
||||
|
||||
SecTrustResultType result;
|
||||
__Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out);
|
||||
|
||||
[trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
|
||||
|
||||
_out:
|
||||
if (trust) {
|
||||
CFRelease(trust);
|
||||
}
|
||||
|
||||
if (certificates) {
|
||||
CFRelease(certificates);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
CFRelease(policy);
|
||||
|
||||
return [NSArray arrayWithArray:trustChain];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@interface AFSecurityPolicy()
|
||||
@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
|
||||
@property (readwrite, nonatomic, strong) NSArray *pinnedPublicKeys;
|
||||
@end
|
||||
|
||||
@implementation AFSecurityPolicy
|
||||
|
||||
+ (NSArray *)defaultPinnedCertificates {
|
||||
static NSArray *_defaultPinnedCertificates = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
|
||||
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
|
||||
|
||||
NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]];
|
||||
for (NSString *path in paths) {
|
||||
NSData *certificateData = [NSData dataWithContentsOfFile:path];
|
||||
[certificates addObject:certificateData];
|
||||
}
|
||||
|
||||
_defaultPinnedCertificates = [[NSArray alloc] initWithArray:certificates];
|
||||
});
|
||||
|
||||
return _defaultPinnedCertificates;
|
||||
}
|
||||
|
||||
+ (instancetype)defaultPolicy {
|
||||
AFSecurityPolicy *securityPolicy = [[self alloc] init];
|
||||
securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
|
||||
|
||||
return securityPolicy;
|
||||
}
|
||||
|
||||
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode {
|
||||
AFSecurityPolicy *securityPolicy = [[self alloc] init];
|
||||
securityPolicy.SSLPinningMode = pinningMode;
|
||||
|
||||
[securityPolicy setPinnedCertificates:[self defaultPinnedCertificates]];
|
||||
|
||||
return securityPolicy;
|
||||
}
|
||||
|
||||
- (id)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.validatesDomainName = YES;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)setPinnedCertificates:(NSArray *)pinnedCertificates {
|
||||
_pinnedCertificates = [[NSOrderedSet orderedSetWithArray:pinnedCertificates] array];
|
||||
|
||||
if (self.pinnedCertificates) {
|
||||
NSMutableArray *mutablePinnedPublicKeys = [NSMutableArray arrayWithCapacity:[self.pinnedCertificates count]];
|
||||
for (NSData *certificate in self.pinnedCertificates) {
|
||||
id publicKey = AFPublicKeyForCertificate(certificate);
|
||||
if (!publicKey) {
|
||||
continue;
|
||||
}
|
||||
[mutablePinnedPublicKeys addObject:publicKey];
|
||||
}
|
||||
self.pinnedPublicKeys = [NSArray arrayWithArray:mutablePinnedPublicKeys];
|
||||
} else {
|
||||
self.pinnedPublicKeys = nil;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust {
|
||||
return [self evaluateServerTrust:serverTrust forDomain:nil];
|
||||
}
|
||||
|
||||
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
|
||||
forDomain:(NSString *)domain
|
||||
{
|
||||
if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) {
|
||||
// https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html
|
||||
// According to the docs, you should only trust your provided certs for evaluation.
|
||||
// Pinned certificates are added to the trust. Without pinned certificates,
|
||||
// there is nothing to evaluate against.
|
||||
//
|
||||
// From Apple Docs:
|
||||
// "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors).
|
||||
// Instead, add your own (self-signed) CA certificate to the list of trusted anchors."
|
||||
NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning.");
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSMutableArray *policies = [NSMutableArray array];
|
||||
if (self.validatesDomainName) {
|
||||
[policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
|
||||
} else {
|
||||
[policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
|
||||
}
|
||||
|
||||
SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
|
||||
|
||||
if (self.SSLPinningMode == AFSSLPinningModeNone) {
|
||||
return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust);
|
||||
} else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust);
|
||||
switch (self.SSLPinningMode) {
|
||||
case AFSSLPinningModeNone:
|
||||
default:
|
||||
return NO;
|
||||
case AFSSLPinningModeCertificate: {
|
||||
NSMutableArray *pinnedCertificates = [NSMutableArray array];
|
||||
for (NSData *certificateData in self.pinnedCertificates) {
|
||||
[pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)];
|
||||
}
|
||||
SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates);
|
||||
|
||||
if (!AFServerTrustIsValid(serverTrust)) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSUInteger trustedCertificateCount = 0;
|
||||
for (NSData *trustChainCertificate in serverCertificates) {
|
||||
if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
|
||||
trustedCertificateCount++;
|
||||
}
|
||||
}
|
||||
return trustedCertificateCount > 0;
|
||||
}
|
||||
case AFSSLPinningModePublicKey: {
|
||||
NSUInteger trustedPublicKeyCount = 0;
|
||||
NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust);
|
||||
|
||||
for (id trustChainPublicKey in publicKeys) {
|
||||
for (id pinnedPublicKey in self.pinnedPublicKeys) {
|
||||
if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
|
||||
trustedPublicKeyCount += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return trustedPublicKeyCount > 0;
|
||||
}
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
#pragma mark - NSKeyValueObserving
|
||||
|
||||
+ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys {
|
||||
return [NSSet setWithObject:@"pinnedCertificates"];
|
||||
}
|
||||
|
||||
#pragma mark - NSSecureCoding
|
||||
|
||||
+ (BOOL)supportsSecureCoding {
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (instancetype)initWithCoder:(NSCoder *)decoder {
|
||||
|
||||
self = [self init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue];
|
||||
self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))];
|
||||
self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))];
|
||||
self.pinnedCertificates = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(pinnedCertificates))];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder {
|
||||
[coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))];
|
||||
[coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))];
|
||||
[coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))];
|
||||
[coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))];
|
||||
}
|
||||
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init];
|
||||
securityPolicy.SSLPinningMode = self.SSLPinningMode;
|
||||
securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates;
|
||||
securityPolicy.validatesDomainName = self.validatesDomainName;
|
||||
securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone];
|
||||
|
||||
return securityPolicy;
|
||||
}
|
||||
|
||||
@end
|
||||
344
Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.h
generated
Normal file
344
Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.h
generated
Normal file
@ -0,0 +1,344 @@
|
||||
// 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
|
||||
792
Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.m
generated
Normal file
792
Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.m
generated
Normal file
@ -0,0 +1,792 @@
|
||||
// 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
|
||||
476
Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h
generated
Normal file
476
Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h
generated
Normal file
@ -0,0 +1,476 @@
|
||||
// AFURLRequestSerialization.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>
|
||||
#if TARGET_OS_IOS
|
||||
#import <UIKit/UIKit.h>
|
||||
#elif TARGET_OS_WATCH
|
||||
#import <WatchKit/WatchKit.h>
|
||||
#endif
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
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`.
|
||||
*/
|
||||
@protocol AFURLRequestSerialization <NSObject, NSSecureCoding, NSCopying>
|
||||
|
||||
/**
|
||||
Returns a request with the specified parameters encoded into a copy of the original request.
|
||||
|
||||
@param request The original request.
|
||||
@param parameters The parameters to be encoded.
|
||||
@param error The error that occurred while attempting to encode the request parameters.
|
||||
|
||||
@return A serialized request.
|
||||
*/
|
||||
- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
|
||||
withParameters:(nullable id)parameters
|
||||
error:(NSError * __nullable __autoreleasing *)error
|
||||
#ifdef NS_SWIFT_NOTHROW
|
||||
NS_SWIFT_NOTHROW
|
||||
#endif
|
||||
;
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
|
||||
*/
|
||||
typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) {
|
||||
AFHTTPRequestQueryStringDefaultStyle = 0,
|
||||
};
|
||||
|
||||
@protocol AFMultipartFormData;
|
||||
|
||||
/**
|
||||
`AFHTTPRequestSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
|
||||
|
||||
Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior.
|
||||
*/
|
||||
@interface AFHTTPRequestSerializer : NSObject <AFURLRequestSerialization>
|
||||
|
||||
/**
|
||||
The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default.
|
||||
*/
|
||||
@property (nonatomic, assign) NSStringEncoding stringEncoding;
|
||||
|
||||
/**
|
||||
Whether created requests can use the device’s cellular radio (if present). `YES` by default.
|
||||
|
||||
@see NSMutableURLRequest -setAllowsCellularAccess:
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL allowsCellularAccess;
|
||||
|
||||
/**
|
||||
The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default.
|
||||
|
||||
@see NSMutableURLRequest -setCachePolicy:
|
||||
*/
|
||||
@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
|
||||
|
||||
/**
|
||||
Whether created requests should use the default cookie handling. `YES` by default.
|
||||
|
||||
@see NSMutableURLRequest -setHTTPShouldHandleCookies:
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL HTTPShouldHandleCookies;
|
||||
|
||||
/**
|
||||
Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default
|
||||
|
||||
@see NSMutableURLRequest -setHTTPShouldUsePipelining:
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL HTTPShouldUsePipelining;
|
||||
|
||||
/**
|
||||
The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default.
|
||||
|
||||
@see NSMutableURLRequest -setNetworkServiceType:
|
||||
*/
|
||||
@property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType;
|
||||
|
||||
/**
|
||||
The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds.
|
||||
|
||||
@see NSMutableURLRequest -setTimeoutInterval:
|
||||
*/
|
||||
@property (nonatomic, assign) NSTimeInterval timeoutInterval;
|
||||
|
||||
///---------------------------------------
|
||||
/// @name Configuring HTTP Request Headers
|
||||
///---------------------------------------
|
||||
|
||||
/**
|
||||
Default HTTP header field values to be applied to serialized requests. By default, these include the following:
|
||||
|
||||
- `Accept-Language` with the contents of `NSLocale +preferredLanguages`
|
||||
- `User-Agent` with the contents of various bundle identifiers and OS designations
|
||||
|
||||
@discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) NSDictionary *HTTPRequestHeaders;
|
||||
|
||||
/**
|
||||
Creates and returns a serializer with default configuration.
|
||||
*/
|
||||
+ (instancetype)serializer;
|
||||
|
||||
/**
|
||||
Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header.
|
||||
|
||||
@param field The HTTP header to set a default value for
|
||||
@param value The value set as default for the specified header, or `nil`
|
||||
*/
|
||||
- (void)setValue:(nullable NSString *)value
|
||||
forHTTPHeaderField:(NSString *)field;
|
||||
|
||||
/**
|
||||
Returns the value for the HTTP headers set in the request serializer.
|
||||
|
||||
@param field The HTTP header to retrieve the default value for
|
||||
|
||||
@return The value set as default for the specified header, or `nil`
|
||||
*/
|
||||
- (nullable NSString *)valueForHTTPHeaderField:(NSString *)field;
|
||||
|
||||
/**
|
||||
Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.
|
||||
|
||||
@param username The HTTP basic auth username
|
||||
@param password The HTTP basic auth password
|
||||
*/
|
||||
- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
|
||||
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.
|
||||
*/
|
||||
- (void)clearAuthorizationHeader;
|
||||
|
||||
///-------------------------------------------------------
|
||||
/// @name Configuring Query String Parameter Serialization
|
||||
///-------------------------------------------------------
|
||||
|
||||
/**
|
||||
HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default.
|
||||
*/
|
||||
@property (nonatomic, strong) NSSet *HTTPMethodsEncodingParametersInURI;
|
||||
|
||||
/**
|
||||
Set the method of query string serialization according to one of the pre-defined styles.
|
||||
|
||||
@param style The serialization style.
|
||||
|
||||
@see AFHTTPRequestQueryStringSerializationStyle
|
||||
*/
|
||||
- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style;
|
||||
|
||||
/**
|
||||
Set the a custom method of query string serialization according to the specified block.
|
||||
|
||||
@param block A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occurred when attempting to encode parameters for the given request.
|
||||
*/
|
||||
- (void)setQueryStringSerializationWithBlock:(nullable NSString * (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block;
|
||||
|
||||
///-------------------------------
|
||||
/// @name Creating Request Objects
|
||||
///-------------------------------
|
||||
|
||||
/**
|
||||
@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.
|
||||
|
||||
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.
|
||||
|
||||
@param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`.
|
||||
@param URLString The URL string used to create the request URL.
|
||||
@param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
|
||||
@param error The error that occurred while constructing the request.
|
||||
|
||||
@return An `NSMutableURLRequest` object.
|
||||
*/
|
||||
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
|
||||
URLString:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
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
|
||||
|
||||
Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream.
|
||||
|
||||
@param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`.
|
||||
@param URLString The URL string used to create the request URL.
|
||||
@param parameters The parameters to be encoded and set in the request HTTP body.
|
||||
@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 error The error that occurred while constructing the request.
|
||||
|
||||
@return An `NSMutableURLRequest` object
|
||||
*/
|
||||
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
|
||||
URLString:(NSString *)URLString
|
||||
parameters:(nullable NSDictionary *)parameters
|
||||
constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
|
||||
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.
|
||||
|
||||
@param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`.
|
||||
@param fileURL The file URL to write multipart form contents to.
|
||||
@param handler A handler block to execute.
|
||||
|
||||
@discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request.
|
||||
|
||||
@see https://github.com/AFNetworking/AFNetworking/issues/1398
|
||||
*/
|
||||
- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
|
||||
writingStreamContentsToFile:(NSURL *)fileURL
|
||||
completionHandler:(nullable void (^)(NSError * __nullable error))handler;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`.
|
||||
*/
|
||||
@protocol AFMultipartFormData
|
||||
|
||||
/**
|
||||
Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary.
|
||||
|
||||
The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively.
|
||||
|
||||
@param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
|
||||
@param name The name to be associated with the specified data. This parameter must not be `nil`.
|
||||
@param error If an error occurs, upon return contains an `NSError` object that describes the problem.
|
||||
|
||||
@return `YES` if the file data was successfully appended, otherwise `NO`.
|
||||
*/
|
||||
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
|
||||
name:(NSString *)name
|
||||
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.
|
||||
|
||||
@param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
|
||||
@param name The name to be associated with the specified data. This parameter must not be `nil`.
|
||||
@param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`.
|
||||
@param mimeType The declared MIME type of the file data. This parameter must not be `nil`.
|
||||
@param error If an error occurs, upon return contains an `NSError` object that describes the problem.
|
||||
|
||||
@return `YES` if the file data was successfully appended otherwise `NO`.
|
||||
*/
|
||||
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
|
||||
name:(NSString *)name
|
||||
fileName:(NSString *)fileName
|
||||
mimeType:(NSString *)mimeType
|
||||
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.
|
||||
|
||||
@param inputStream The input stream to be appended to the form data
|
||||
@param name The name to be associated with the specified input stream. This parameter must not be `nil`.
|
||||
@param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`.
|
||||
@param length The length of the specified input stream in bytes.
|
||||
@param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
|
||||
*/
|
||||
- (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream
|
||||
name:(NSString *)name
|
||||
fileName:(NSString *)fileName
|
||||
length:(int64_t)length
|
||||
mimeType:(NSString *)mimeType;
|
||||
|
||||
/**
|
||||
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.
|
||||
|
||||
@param data The data to be encoded and appended to the form data.
|
||||
@param name The name to be associated with the specified data. This parameter must not be `nil`.
|
||||
@param fileName The filename to be associated with the specified data. This parameter must not be `nil`.
|
||||
@param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
|
||||
*/
|
||||
- (void)appendPartWithFileData:(NSData *)data
|
||||
name:(NSString *)name
|
||||
fileName:(NSString *)fileName
|
||||
mimeType:(NSString *)mimeType;
|
||||
|
||||
/**
|
||||
Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
|
||||
|
||||
@param data The data to be encoded and appended to the form data.
|
||||
@param name The name to be associated with the specified data. This parameter must not be `nil`.
|
||||
*/
|
||||
|
||||
- (void)appendPartWithFormData:(NSData *)data
|
||||
name:(NSString *)name;
|
||||
|
||||
|
||||
/**
|
||||
Appends HTTP headers, followed by the encoded data and the multipart form boundary.
|
||||
|
||||
@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`.
|
||||
*/
|
||||
- (void)appendPartWithHeaders:(nullable NSDictionary *)headers
|
||||
body:(NSData *)body;
|
||||
|
||||
/**
|
||||
Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
|
||||
|
||||
When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.
|
||||
|
||||
@param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb.
|
||||
@param delay Duration of delay each time a packet is read. By default, no delay is set.
|
||||
*/
|
||||
- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
|
||||
delay:(NSTimeInterval)delay;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`.
|
||||
*/
|
||||
@interface AFJSONRequestSerializer : AFHTTPRequestSerializer
|
||||
|
||||
/**
|
||||
Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default.
|
||||
*/
|
||||
@property (nonatomic, assign) NSJSONWritingOptions writingOptions;
|
||||
|
||||
/**
|
||||
Creates and returns a JSON serializer with specified reading and writing options.
|
||||
|
||||
@param writingOptions The specified JSON writing options.
|
||||
*/
|
||||
+ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFPropertyListRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`.
|
||||
*/
|
||||
@interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer
|
||||
|
||||
/**
|
||||
The property list format. Possible values are described in "NSPropertyListFormat".
|
||||
*/
|
||||
@property (nonatomic, assign) NSPropertyListFormat format;
|
||||
|
||||
/**
|
||||
@warning The `writeOptions` property is currently unused.
|
||||
*/
|
||||
@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions;
|
||||
|
||||
/**
|
||||
Creates and returns a property list serializer with a specified format, read options, and write options.
|
||||
|
||||
@param format The property list format.
|
||||
@param writeOptions The property list write options.
|
||||
|
||||
@warning The `writeOptions` property is currently unused.
|
||||
*/
|
||||
+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
|
||||
writeOptions:(NSPropertyListWriteOptions)writeOptions;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
///----------------
|
||||
/// @name Constants
|
||||
///----------------
|
||||
|
||||
/**
|
||||
## Error Domains
|
||||
|
||||
The following error domain is predefined.
|
||||
|
||||
- `NSString * const AFURLRequestSerializationErrorDomain`
|
||||
|
||||
### Constants
|
||||
|
||||
`AFURLRequestSerializationErrorDomain`
|
||||
AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain;
|
||||
|
||||
/**
|
||||
## User info dictionary keys
|
||||
|
||||
These keys may exist in the user info dictionary, in addition to those defined for NSError.
|
||||
|
||||
- `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
|
||||
|
||||
### Constants
|
||||
|
||||
`AFNetworkingOperationFailingURLRequestErrorKey`
|
||||
The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey;
|
||||
|
||||
/**
|
||||
## Throttling Bandwidth for HTTP Request Input Streams
|
||||
|
||||
@see -throttleBandwidthWithPacketSize:delay:
|
||||
|
||||
### Constants
|
||||
|
||||
`kAFUploadStream3GSuggestedPacketSize`
|
||||
Maximum packet size, in number of bytes. Equal to 16kb.
|
||||
|
||||
`kAFUploadStream3GSuggestedDelay`
|
||||
Duration of delay each time a packet is read. Equal to 0.2 seconds.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize;
|
||||
FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay;
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
1428
Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m
generated
Normal file
1428
Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m
generated
Normal file
File diff suppressed because it is too large
Load Diff
315
Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h
generated
Normal file
315
Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h
generated
Normal file
@ -0,0 +1,315 @@
|
||||
// AFURLResponseSerialization.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 <CoreGraphics/CoreGraphics.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data.
|
||||
|
||||
For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object.
|
||||
*/
|
||||
@protocol AFURLResponseSerialization <NSObject, NSSecureCoding, NSCopying>
|
||||
|
||||
/**
|
||||
The response object decoded from the data associated with a specified response.
|
||||
|
||||
@param response The response to be processed.
|
||||
@param data The response data to be decoded.
|
||||
@param error The error that occurred while attempting to decode the response data.
|
||||
|
||||
@return The object decoded from the specified response data.
|
||||
*/
|
||||
- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response
|
||||
data:(nullable NSData *)data
|
||||
error:(NSError * __nullable __autoreleasing *)error
|
||||
#ifdef NS_SWIFT_NOTHROW
|
||||
NS_SWIFT_NOTHROW
|
||||
#endif
|
||||
;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFHTTPResponseSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
|
||||
|
||||
Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior.
|
||||
*/
|
||||
@interface AFHTTPResponseSerializer : NSObject <AFURLResponseSerialization>
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
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.
|
||||
*/
|
||||
+ (instancetype)serializer;
|
||||
|
||||
///-----------------------------------------
|
||||
/// @name Configuring Response Serialization
|
||||
///-----------------------------------------
|
||||
|
||||
/**
|
||||
The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation.
|
||||
|
||||
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
|
||||
*/
|
||||
@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes;
|
||||
|
||||
/**
|
||||
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 *acceptableContentTypes;
|
||||
|
||||
/**
|
||||
Validates the specified response and data.
|
||||
|
||||
In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks.
|
||||
|
||||
@param response The response to be validated.
|
||||
@param data The data associated with the response.
|
||||
@param error The error that occurred while attempting to validate the response.
|
||||
|
||||
@return `YES` if the response is valid, otherwise `NO`.
|
||||
*/
|
||||
- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response
|
||||
data:(nullable NSData *)data
|
||||
error:(NSError * __nullable __autoreleasing *)error;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
|
||||
/**
|
||||
`AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses.
|
||||
|
||||
By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
|
||||
|
||||
- `application/json`
|
||||
- `text/json`
|
||||
- `text/javascript`
|
||||
*/
|
||||
@interface AFJSONResponseSerializer : AFHTTPResponseSerializer
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
|
||||
*/
|
||||
@property (nonatomic, assign) NSJSONReadingOptions readingOptions;
|
||||
|
||||
/**
|
||||
Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`.
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL removesKeysWithNullValues;
|
||||
|
||||
/**
|
||||
Creates and returns a JSON serializer with specified reading and writing options.
|
||||
|
||||
@param readingOptions The specified JSON reading options.
|
||||
*/
|
||||
+ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects.
|
||||
|
||||
By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
|
||||
|
||||
- `application/xml`
|
||||
- `text/xml`
|
||||
*/
|
||||
@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
|
||||
|
||||
/**
|
||||
`AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
|
||||
|
||||
By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
|
||||
|
||||
- `application/xml`
|
||||
- `text/xml`
|
||||
*/
|
||||
@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
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;
|
||||
|
||||
/**
|
||||
Creates and returns an XML document serializer with the specified options.
|
||||
|
||||
@param mask The XML document options.
|
||||
*/
|
||||
+ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask;
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
|
||||
|
||||
By default, `AFPropertyListResponseSerializer` accepts the following MIME types:
|
||||
|
||||
- `application/x-plist`
|
||||
*/
|
||||
@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
The property list format. Possible values are described in "NSPropertyListFormat".
|
||||
*/
|
||||
@property (nonatomic, assign) NSPropertyListFormat format;
|
||||
|
||||
/**
|
||||
The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions."
|
||||
*/
|
||||
@property (nonatomic, assign) NSPropertyListReadOptions readOptions;
|
||||
|
||||
/**
|
||||
Creates and returns a property list serializer with a specified format, read options, and write options.
|
||||
|
||||
@param format The property list format.
|
||||
@param readOptions The property list reading options.
|
||||
*/
|
||||
+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
|
||||
readOptions:(NSPropertyListReadOptions)readOptions;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses.
|
||||
|
||||
By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
|
||||
|
||||
- `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`
|
||||
*/
|
||||
@interface AFImageResponseSerializer : AFHTTPResponseSerializer
|
||||
|
||||
#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.
|
||||
*/
|
||||
@property (nonatomic, assign) CGFloat imageScale;
|
||||
|
||||
/**
|
||||
Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default.
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage;
|
||||
#endif
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFCompoundSerializer` is a subclass of `AFHTTPResponseSerializer` that delegates the response serialization to the first `AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer.
|
||||
*/
|
||||
@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer
|
||||
|
||||
/**
|
||||
The component response serializers.
|
||||
*/
|
||||
@property (readonly, nonatomic, copy) NSArray *responseSerializers;
|
||||
|
||||
/**
|
||||
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:`.
|
||||
*/
|
||||
+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers;
|
||||
|
||||
@end
|
||||
|
||||
///----------------
|
||||
/// @name Constants
|
||||
///----------------
|
||||
|
||||
/**
|
||||
## Error Domains
|
||||
|
||||
The following error domain is predefined.
|
||||
|
||||
- `NSString * const AFURLResponseSerializationErrorDomain`
|
||||
|
||||
### Constants
|
||||
|
||||
`AFURLResponseSerializationErrorDomain`
|
||||
AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain;
|
||||
|
||||
/**
|
||||
## User info dictionary keys
|
||||
|
||||
These keys may exist in the user info dictionary, in addition to those defined for NSError.
|
||||
|
||||
- `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
|
||||
- `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey`
|
||||
|
||||
### Constants
|
||||
|
||||
`AFNetworkingOperationFailingURLResponseErrorKey`
|
||||
The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
|
||||
|
||||
`AFNetworkingOperationFailingURLResponseDataErrorKey`
|
||||
The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey;
|
||||
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey;
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
825
Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m
generated
Normal file
825
Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m
generated
Normal file
@ -0,0 +1,825 @@
|
||||
// AFURLResponseSerialization.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 "AFURLResponseSerialization.h"
|
||||
|
||||
#if TARGET_OS_IOS
|
||||
#import <UIKit/UIKit.h>
|
||||
#elif TARGET_OS_WATCH
|
||||
#import <WatchKit/WatchKit.h>
|
||||
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#endif
|
||||
|
||||
NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response";
|
||||
NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response";
|
||||
NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data";
|
||||
|
||||
static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) {
|
||||
if (!error) {
|
||||
return underlyingError;
|
||||
}
|
||||
|
||||
if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) {
|
||||
return error;
|
||||
}
|
||||
|
||||
NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy];
|
||||
mutableUserInfo[NSUnderlyingErrorKey] = underlyingError;
|
||||
|
||||
return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo];
|
||||
}
|
||||
|
||||
static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) {
|
||||
if ([error.domain isEqualToString:domain] && error.code == code) {
|
||||
return YES;
|
||||
} else if (error.userInfo[NSUnderlyingErrorKey]) {
|
||||
return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain);
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) {
|
||||
if ([JSONObject isKindOfClass:[NSArray class]]) {
|
||||
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
|
||||
for (id value in (NSArray *)JSONObject) {
|
||||
[mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)];
|
||||
}
|
||||
|
||||
return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray];
|
||||
} else if ([JSONObject isKindOfClass:[NSDictionary class]]) {
|
||||
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject];
|
||||
for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) {
|
||||
id value = (NSDictionary *)JSONObject[key];
|
||||
if (!value || [value isEqual:[NSNull null]]) {
|
||||
[mutableDictionary removeObjectForKey:key];
|
||||
} else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
|
||||
mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions);
|
||||
}
|
||||
}
|
||||
|
||||
return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary];
|
||||
}
|
||||
|
||||
return JSONObject;
|
||||
}
|
||||
|
||||
@implementation AFHTTPResponseSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
return [[self alloc] init];
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.stringEncoding = NSUTF8StringEncoding;
|
||||
|
||||
self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
|
||||
self.acceptableContentTypes = nil;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (BOOL)validateResponse:(NSHTTPURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
BOOL responseIsValid = YES;
|
||||
NSError *validationError = nil;
|
||||
|
||||
if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) {
|
||||
if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]]) {
|
||||
if ([data length] > 0 && [response URL]) {
|
||||
NSMutableDictionary *mutableUserInfo = [@{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]],
|
||||
NSURLErrorFailingURLErrorKey:[response URL],
|
||||
AFNetworkingOperationFailingURLResponseErrorKey: response,
|
||||
} mutableCopy];
|
||||
if (data) {
|
||||
mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
|
||||
}
|
||||
|
||||
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError);
|
||||
}
|
||||
|
||||
responseIsValid = NO;
|
||||
}
|
||||
|
||||
if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) {
|
||||
NSMutableDictionary *mutableUserInfo = [@{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
|
||||
NSURLErrorFailingURLErrorKey:[response URL],
|
||||
AFNetworkingOperationFailingURLResponseErrorKey: response,
|
||||
} mutableCopy];
|
||||
|
||||
if (data) {
|
||||
mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
|
||||
}
|
||||
|
||||
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
|
||||
|
||||
responseIsValid = NO;
|
||||
}
|
||||
}
|
||||
|
||||
if (error && !responseIsValid) {
|
||||
*error = validationError;
|
||||
}
|
||||
|
||||
return responseIsValid;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
[self validateResponse:(NSHTTPURLResponse *)response data:data error:error];
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
#pragma mark - NSSecureCoding
|
||||
|
||||
+ (BOOL)supportsSecureCoding {
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (id)initWithCoder:(NSCoder *)decoder {
|
||||
self = [self init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
|
||||
self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder {
|
||||
[coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
|
||||
[coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
|
||||
}
|
||||
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (id)copyWithZone:(NSZone *)zone {
|
||||
AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone];
|
||||
serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone];
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation AFJSONResponseSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
return [self serializerWithReadingOptions:(NSJSONReadingOptions)0];
|
||||
}
|
||||
|
||||
+ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions {
|
||||
AFJSONResponseSerializer *serializer = [[self alloc] init];
|
||||
serializer.readingOptions = readingOptions;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
NSStringEncoding stringEncoding = self.stringEncoding;
|
||||
if (response.textEncodingName) {
|
||||
CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
|
||||
if (encoding != kCFStringEncodingInvalidId) {
|
||||
stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
|
||||
}
|
||||
}
|
||||
|
||||
id responseObject = nil;
|
||||
NSError *serializationError = nil;
|
||||
@autoreleasepool {
|
||||
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 (data) {
|
||||
if ([data length] > 0) {
|
||||
responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
|
||||
} 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];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (self.removesKeysWithNullValues && responseObject) {
|
||||
responseObject = AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
*error = AFErrorWithUnderlyingError(serializationError, *error);
|
||||
}
|
||||
|
||||
return responseObject;
|
||||
}
|
||||
|
||||
#pragma mark - NSSecureCoding
|
||||
|
||||
- (id)initWithCoder:(NSCoder *)decoder {
|
||||
self = [super initWithCoder:decoder];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue];
|
||||
self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder {
|
||||
[super encodeWithCoder:coder];
|
||||
|
||||
[coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))];
|
||||
[coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))];
|
||||
}
|
||||
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (id)copyWithZone:(NSZone *)zone {
|
||||
AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
serializer.readingOptions = self.readingOptions;
|
||||
serializer.removesKeysWithNullValues = self.removesKeysWithNullValues;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation AFXMLParserResponseSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
AFXMLParserResponseSerializer *serializer = [[self alloc] init];
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSHTTPURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
return [[NSXMLParser alloc] initWithData:data];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
|
||||
|
||||
@implementation AFXMLDocumentResponseSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
return [self serializerWithXMLDocumentOptions:0];
|
||||
}
|
||||
|
||||
+ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask {
|
||||
AFXMLDocumentResponseSerializer *serializer = [[self alloc] init];
|
||||
serializer.options = mask;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
NSError *serializationError = nil;
|
||||
NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError];
|
||||
|
||||
if (error) {
|
||||
*error = AFErrorWithUnderlyingError(serializationError, *error);
|
||||
}
|
||||
|
||||
return document;
|
||||
}
|
||||
|
||||
#pragma mark - NSSecureCoding
|
||||
|
||||
- (id)initWithCoder:(NSCoder *)decoder {
|
||||
self = [super initWithCoder:decoder];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder {
|
||||
[super encodeWithCoder:coder];
|
||||
|
||||
[coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))];
|
||||
}
|
||||
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (id)copyWithZone:(NSZone *)zone {
|
||||
AFXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
serializer.options = self.options;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation AFPropertyListResponseSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0];
|
||||
}
|
||||
|
||||
+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
|
||||
readOptions:(NSPropertyListReadOptions)readOptions
|
||||
{
|
||||
AFPropertyListResponseSerializer *serializer = [[self alloc] init];
|
||||
serializer.format = format;
|
||||
serializer.readOptions = readOptions;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
id responseObject;
|
||||
NSError *serializationError = nil;
|
||||
|
||||
if (data) {
|
||||
responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError];
|
||||
}
|
||||
|
||||
if (error) {
|
||||
*error = AFErrorWithUnderlyingError(serializationError, *error);
|
||||
}
|
||||
|
||||
return responseObject;
|
||||
}
|
||||
|
||||
#pragma mark - NSSecureCoding
|
||||
|
||||
- (id)initWithCoder:(NSCoder *)decoder {
|
||||
self = [super initWithCoder:decoder];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
|
||||
self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder {
|
||||
[super encodeWithCoder:coder];
|
||||
|
||||
[coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))];
|
||||
[coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))];
|
||||
}
|
||||
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (id)copyWithZone:(NSZone *)zone {
|
||||
AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
serializer.format = self.format;
|
||||
serializer.readOptions = self.readOptions;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
#import <CoreGraphics/CoreGraphics.h>
|
||||
|
||||
@interface UIImage (AFNetworkingSafeImageLoading)
|
||||
+ (UIImage *)af_safeImageWithData:(NSData *)data;
|
||||
@end
|
||||
|
||||
static NSLock* imageLock = nil;
|
||||
|
||||
@implementation UIImage (AFNetworkingSafeImageLoading)
|
||||
|
||||
+ (UIImage *)af_safeImageWithData:(NSData *)data {
|
||||
UIImage* image = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
imageLock = [[NSLock alloc] init];
|
||||
});
|
||||
|
||||
[imageLock lock];
|
||||
image = [UIImage imageWithData:data];
|
||||
[imageLock unlock];
|
||||
return image;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) {
|
||||
UIImage *image = [UIImage af_safeImageWithData:data];
|
||||
if (image.images) {
|
||||
return image;
|
||||
}
|
||||
|
||||
return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation];
|
||||
}
|
||||
|
||||
static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) {
|
||||
if (!data || [data length] == 0) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
CGImageRef imageRef = NULL;
|
||||
CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
|
||||
|
||||
if ([response.MIMEType isEqualToString:@"image/png"]) {
|
||||
imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
|
||||
} else if ([response.MIMEType isEqualToString:@"image/jpeg"]) {
|
||||
imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
|
||||
|
||||
if (imageRef) {
|
||||
CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef);
|
||||
CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace);
|
||||
|
||||
// CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale
|
||||
if (imageColorSpaceModel == kCGColorSpaceModelCMYK) {
|
||||
CGImageRelease(imageRef);
|
||||
imageRef = NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CGDataProviderRelease(dataProvider);
|
||||
|
||||
UIImage *image = AFImageWithDataAtScale(data, scale);
|
||||
if (!imageRef) {
|
||||
if (image.images || !image) {
|
||||
return image;
|
||||
}
|
||||
|
||||
imageRef = CGImageCreateCopy([image CGImage]);
|
||||
if (!imageRef) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
size_t width = CGImageGetWidth(imageRef);
|
||||
size_t height = CGImageGetHeight(imageRef);
|
||||
size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
|
||||
|
||||
if (width * height > 1024 * 1024 || bitsPerComponent > 8) {
|
||||
CGImageRelease(imageRef);
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
// CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate
|
||||
size_t bytesPerRow = 0;
|
||||
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
|
||||
CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace);
|
||||
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
|
||||
|
||||
if (colorSpaceModel == kCGColorSpaceModelRGB) {
|
||||
uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask);
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wassign-enum"
|
||||
if (alpha == kCGImageAlphaNone) {
|
||||
bitmapInfo &= ~kCGBitmapAlphaInfoMask;
|
||||
bitmapInfo |= kCGImageAlphaNoneSkipFirst;
|
||||
} else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) {
|
||||
bitmapInfo &= ~kCGBitmapAlphaInfoMask;
|
||||
bitmapInfo |= kCGImageAlphaPremultipliedFirst;
|
||||
}
|
||||
#pragma clang diagnostic pop
|
||||
}
|
||||
|
||||
CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
|
||||
|
||||
CGColorSpaceRelease(colorSpace);
|
||||
|
||||
if (!context) {
|
||||
CGImageRelease(imageRef);
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef);
|
||||
CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context);
|
||||
|
||||
CGContextRelease(context);
|
||||
|
||||
UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation];
|
||||
|
||||
CGImageRelease(inflatedImageRef);
|
||||
CGImageRelease(imageRef);
|
||||
|
||||
return inflatedImage;
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@implementation AFImageResponseSerializer
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return 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
|
||||
self.imageScale = [[UIScreen mainScreen] scale];
|
||||
self.automaticallyInflatesResponseImage = YES;
|
||||
#elif TARGET_OS_WATCH
|
||||
self.imageScale = [[WKInterfaceDevice currentDevice] screenScale];
|
||||
self.automaticallyInflatesResponseImage = YES;
|
||||
#endif
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerializer
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
if (self.automaticallyInflatesResponseImage) {
|
||||
return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale);
|
||||
} else {
|
||||
return AFImageWithDataAtScale(data, self.imageScale);
|
||||
}
|
||||
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
||||
// Ensure that the image is set to it's correct pixel width and height
|
||||
NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data];
|
||||
NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
|
||||
[image addRepresentation:bitimage];
|
||||
|
||||
return image;
|
||||
#endif
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
#pragma mark - NSSecureCoding
|
||||
|
||||
- (id)initWithCoder:(NSCoder *)decoder {
|
||||
self = [super initWithCoder:decoder];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))];
|
||||
#if CGFLOAT_IS_DOUBLE
|
||||
self.imageScale = [imageScale doubleValue];
|
||||
#else
|
||||
self.imageScale = [imageScale floatValue];
|
||||
#endif
|
||||
|
||||
self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
|
||||
#endif
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder {
|
||||
[super encodeWithCoder:coder];
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
[coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))];
|
||||
[coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
|
||||
#endif
|
||||
}
|
||||
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (id)copyWithZone:(NSZone *)zone {
|
||||
AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
serializer.imageScale = self.imageScale;
|
||||
serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage;
|
||||
#endif
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@interface AFCompoundResponseSerializer ()
|
||||
@property (readwrite, nonatomic, copy) NSArray *responseSerializers;
|
||||
@end
|
||||
|
||||
@implementation AFCompoundResponseSerializer
|
||||
|
||||
+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers {
|
||||
AFCompoundResponseSerializer *serializer = [[self alloc] init];
|
||||
serializer.responseSerializers = responseSerializers;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
for (id <AFURLResponseSerialization> serializer in self.responseSerializers) {
|
||||
if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
NSError *serializerError = nil;
|
||||
id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError];
|
||||
if (responseObject) {
|
||||
if (error) {
|
||||
*error = AFErrorWithUnderlyingError(serializerError, *error);
|
||||
}
|
||||
|
||||
return responseObject;
|
||||
}
|
||||
}
|
||||
|
||||
return [super responseObjectForResponse:response data:data error:error];
|
||||
}
|
||||
|
||||
#pragma mark - NSSecureCoding
|
||||
|
||||
- (id)initWithCoder:(NSCoder *)decoder {
|
||||
self = [super initWithCoder:decoder];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.responseSerializers = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(responseSerializers))];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder {
|
||||
[super encodeWithCoder:coder];
|
||||
|
||||
[coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))];
|
||||
}
|
||||
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (id)copyWithZone:(NSZone *)zone {
|
||||
AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
serializer.responseSerializers = self.responseSerializers;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
@end
|
||||
554
Pods/AFNetworking/AFNetworking/AFURLSessionManager.h
generated
Normal file
554
Pods/AFNetworking/AFNetworking/AFURLSessionManager.h
generated
Normal file
@ -0,0 +1,554 @@
|
||||
// AFURLSessionManager.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 "AFURLResponseSerialization.h"
|
||||
#import "AFURLRequestSerialization.h"
|
||||
#import "AFSecurityPolicy.h"
|
||||
#if !TARGET_OS_WATCH
|
||||
#import "AFNetworkReachabilityManager.h"
|
||||
#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>`.
|
||||
|
||||
## Subclassing Notes
|
||||
|
||||
This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead.
|
||||
|
||||
## NSURLSession & NSURLSessionTask Delegate Methods
|
||||
|
||||
`AFURLSessionManager` implements the following delegate methods:
|
||||
|
||||
### `NSURLSessionDelegate`
|
||||
|
||||
- `URLSession:didBecomeInvalidWithError:`
|
||||
- `URLSession:didReceiveChallenge:completionHandler:`
|
||||
- `URLSessionDidFinishEventsForBackgroundURLSession:`
|
||||
|
||||
### `NSURLSessionTaskDelegate`
|
||||
|
||||
- `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`
|
||||
- `URLSession:task:didReceiveChallenge:completionHandler:`
|
||||
- `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`
|
||||
- `URLSession:task:didCompleteWithError:`
|
||||
|
||||
### `NSURLSessionDataDelegate`
|
||||
|
||||
- `URLSession:dataTask:didReceiveResponse:completionHandler:`
|
||||
- `URLSession:dataTask:didBecomeDownloadTask:`
|
||||
- `URLSession:dataTask:didReceiveData:`
|
||||
- `URLSession:dataTask:willCacheResponse:completionHandler:`
|
||||
|
||||
### `NSURLSessionDownloadDelegate`
|
||||
|
||||
- `URLSession:downloadTask:didFinishDownloadingToURL:`
|
||||
- `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`
|
||||
- `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`
|
||||
|
||||
If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
|
||||
|
||||
## 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.
|
||||
|
||||
## NSCoding Caveats
|
||||
|
||||
- Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`.
|
||||
|
||||
## NSCopying Caveats
|
||||
|
||||
- `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original.
|
||||
- Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied.
|
||||
|
||||
@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.
|
||||
*/
|
||||
|
||||
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>
|
||||
|
||||
/**
|
||||
The managed session.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) NSURLSession *session;
|
||||
|
||||
/**
|
||||
The operation queue on which delegate callbacks are run.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;
|
||||
|
||||
/**
|
||||
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 instance of `AFJSONResponseSerializer`.
|
||||
|
||||
@warning `responseSerializer` must not be `nil`.
|
||||
*/
|
||||
@property (nonatomic, strong) id <AFURLResponseSerialization> responseSerializer;
|
||||
|
||||
///-------------------------------
|
||||
/// @name Managing Security Policy
|
||||
///-------------------------------
|
||||
|
||||
/**
|
||||
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;
|
||||
|
||||
#if !TARGET_OS_WATCH
|
||||
///--------------------------------------
|
||||
/// @name Monitoring Network Reachability
|
||||
///--------------------------------------
|
||||
|
||||
/**
|
||||
The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default.
|
||||
*/
|
||||
@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
|
||||
#endif
|
||||
|
||||
///----------------------------
|
||||
/// @name Getting Session Tasks
|
||||
///----------------------------
|
||||
|
||||
/**
|
||||
The data, upload, and download tasks currently run by the managed session.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) NSArray *tasks;
|
||||
|
||||
/**
|
||||
The data tasks currently run by the managed session.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) NSArray *dataTasks;
|
||||
|
||||
/**
|
||||
The upload tasks currently run by the managed session.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) NSArray *uploadTasks;
|
||||
|
||||
/**
|
||||
The download tasks currently run by the managed session.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) NSArray *downloadTasks;
|
||||
|
||||
///-------------------------------
|
||||
/// @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 Working Around System Bugs
|
||||
///---------------------------------
|
||||
|
||||
/**
|
||||
Whether to attempt to retry creation of upload tasks for background sessions when initial call returns `nil`. `NO` by default.
|
||||
|
||||
@bug As of iOS 7.0, there is a bug where upload tasks created for background tasks are sometimes `nil`. As a workaround, if this property is `YES`, AFNetworking will follow Apple's recommendation to try creating the task again.
|
||||
|
||||
@see https://github.com/AFNetworking/AFNetworking/issues/1675
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL attemptsToRecreateUploadTasksForBackgroundSessions;
|
||||
|
||||
///---------------------
|
||||
/// @name Initialization
|
||||
///---------------------
|
||||
|
||||
/**
|
||||
Creates and returns a manager for a session created with the specified configuration. This is the designated initializer.
|
||||
|
||||
@param configuration The configuration used to create the managed session.
|
||||
|
||||
@return A manager for a newly-created session.
|
||||
*/
|
||||
- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
|
||||
|
||||
/**
|
||||
Invalidates the managed session, optionally canceling pending tasks.
|
||||
|
||||
@param cancelPendingTasks Whether or not to cancel pending tasks.
|
||||
*/
|
||||
- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks;
|
||||
|
||||
///-------------------------
|
||||
/// @name Running Data Tasks
|
||||
///-------------------------
|
||||
|
||||
/**
|
||||
Creates an `NSURLSessionDataTask` with the specified request.
|
||||
|
||||
@param request The HTTP request for the request.
|
||||
@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
|
||||
completionHandler:(nullable void (^)(NSURLResponse *response, id __nullable responseObject, NSError * __nullable error))completionHandler;
|
||||
|
||||
///---------------------------
|
||||
/// @name Running Upload Tasks
|
||||
///---------------------------
|
||||
|
||||
/**
|
||||
Creates an `NSURLSessionUploadTask` with the specified request for a local file.
|
||||
|
||||
@param request The HTTP request for the request.
|
||||
@param fileURL A URL to the local file to be uploaded.
|
||||
@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.
|
||||
|
||||
@see `attemptsToRecreateUploadTasksForBackgroundSessions`
|
||||
*/
|
||||
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
|
||||
fromFile:(NSURL *)fileURL
|
||||
progress:(NSProgress * __nullable __autoreleasing * __nullable)progress
|
||||
completionHandler:(nullable void (^)(NSURLResponse *response, id __nullable responseObject, NSError * __nullable error))completionHandler;
|
||||
|
||||
/**
|
||||
Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body.
|
||||
|
||||
@param request The HTTP request for the request.
|
||||
@param bodyData A data object containing the HTTP body to be uploaded.
|
||||
@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.
|
||||
*/
|
||||
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
|
||||
fromData:(nullable NSData *)bodyData
|
||||
progress:(NSProgress * __nullable __autoreleasing * __nullable)progress
|
||||
completionHandler:(nullable void (^)(NSURLResponse *response, id __nullable responseObject, NSError * __nullable error))completionHandler;
|
||||
|
||||
/**
|
||||
Creates an `NSURLSessionUploadTask` with the specified streaming request.
|
||||
|
||||
@param request The HTTP request for the request.
|
||||
@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.
|
||||
*/
|
||||
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
|
||||
progress:(NSProgress * __nullable __autoreleasing * __nullable)progress
|
||||
completionHandler:(nullable void (^)(NSURLResponse *response, id __nullable responseObject, NSError * __nullable error))completionHandler;
|
||||
|
||||
///-----------------------------
|
||||
/// @name Running Download Tasks
|
||||
///-----------------------------
|
||||
|
||||
/**
|
||||
Creates an `NSURLSessionDownloadTask` with the specified request.
|
||||
|
||||
@param request The HTTP request for the request.
|
||||
@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 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.
|
||||
*/
|
||||
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
|
||||
progress:(NSProgress * __nullable __autoreleasing * __nullable)progress
|
||||
destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
|
||||
completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * __nullable filePath, NSError * __nullable error))completionHandler;
|
||||
|
||||
/**
|
||||
Creates an `NSURLSessionDownloadTask` with the specified resume data.
|
||||
|
||||
@param resumeData The data used to resume downloading.
|
||||
@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 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
|
||||
progress:(NSProgress * __nullable __autoreleasing * __nullable)progress
|
||||
destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
|
||||
completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * __nullable filePath, NSError * __nullable error))completionHandler;
|
||||
|
||||
///---------------------------------
|
||||
/// @name Getting Progress for Tasks
|
||||
///---------------------------------
|
||||
|
||||
/**
|
||||
Returns the upload progress of the specified task.
|
||||
|
||||
@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.
|
||||
*/
|
||||
- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask;
|
||||
|
||||
/**
|
||||
Returns the download progress of the specified task.
|
||||
|
||||
@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.
|
||||
*/
|
||||
- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask;
|
||||
|
||||
///-----------------------------------------
|
||||
/// @name Setting Session Delegate Callbacks
|
||||
///-----------------------------------------
|
||||
|
||||
/**
|
||||
Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`.
|
||||
|
||||
@param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation.
|
||||
*/
|
||||
- (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`.
|
||||
|
||||
@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;
|
||||
|
||||
///--------------------------------------
|
||||
/// @name Setting Task Delegate Callbacks
|
||||
///--------------------------------------
|
||||
|
||||
/**
|
||||
Sets a block to be executed when a task requires a new request body stream to send to the remote server, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:needNewBodyStream:`.
|
||||
|
||||
@param block A block object to be executed when a task requires a new request body stream.
|
||||
*/
|
||||
- (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`.
|
||||
|
||||
@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 * (^)(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:`.
|
||||
|
||||
@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;
|
||||
|
||||
/**
|
||||
Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
|
||||
|
||||
@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 five arguments: the session, the task, 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)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`.
|
||||
|
||||
@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;
|
||||
|
||||
///-------------------------------------------
|
||||
/// @name Setting Data Task Delegate Callbacks
|
||||
///-------------------------------------------
|
||||
|
||||
/**
|
||||
Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
|
||||
|
||||
@param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response.
|
||||
*/
|
||||
- (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`.
|
||||
|
||||
@param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become.
|
||||
*/
|
||||
- (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`.
|
||||
|
||||
@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 session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue.
|
||||
*/
|
||||
- (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`.
|
||||
|
||||
@param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response.
|
||||
*/
|
||||
- (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`.
|
||||
|
||||
@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;
|
||||
|
||||
///-----------------------------------------------
|
||||
/// @name Setting Download Task Delegate Callbacks
|
||||
///-----------------------------------------------
|
||||
|
||||
/**
|
||||
Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`.
|
||||
|
||||
@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;
|
||||
|
||||
/**
|
||||
Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`.
|
||||
|
||||
@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 five arguments: the session, the download task, 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 session manager operation queue.
|
||||
*/
|
||||
- (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
|
||||
|
||||
@param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded.
|
||||
*/
|
||||
- (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block;
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
|
||||
///--------------------
|
||||
/// @name Notifications
|
||||
///--------------------
|
||||
|
||||
/**
|
||||
Posted when a task begins executing.
|
||||
|
||||
@deprecated Use `AFNetworkingTaskDidResumeNotification` instead.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidStartNotification DEPRECATED_ATTRIBUTE;
|
||||
|
||||
/**
|
||||
Posted when a task resumes.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification;
|
||||
|
||||
/**
|
||||
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;
|
||||
|
||||
/**
|
||||
Posted when a task suspends its execution.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification;
|
||||
|
||||
/**
|
||||
Posted when a session is invalidated.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification;
|
||||
|
||||
/**
|
||||
Posted when a session download task encountered an error when moving the temporary download file to a specified destination.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification;
|
||||
|
||||
/**
|
||||
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;
|
||||
|
||||
/**
|
||||
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;
|
||||
|
||||
/**
|
||||
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;
|
||||
|
||||
/**
|
||||
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;
|
||||
|
||||
/**
|
||||
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;
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
1174
Pods/AFNetworking/AFNetworking/AFURLSessionManager.m
generated
Normal file
1174
Pods/AFNetworking/AFNetworking/AFURLSessionManager.m
generated
Normal file
File diff suppressed because it is too large
Load Diff
19
Pods/AFNetworking/LICENSE
generated
Normal file
19
Pods/AFNetworking/LICENSE
generated
Normal file
@ -0,0 +1,19 @@
|
||||
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.
|
||||
394
Pods/AFNetworking/README.md
generated
Normal file
394
Pods/AFNetworking/README.md
generated
Normal file
@ -0,0 +1,394 @@
|
||||
<p align="center" >
|
||||
<img src="https://raw.github.com/AFNetworking/AFNetworking/assets/afnetworking-logo.png" alt="AFNetworking" title="AFNetworking">
|
||||
</p>
|
||||
|
||||
[](https://travis-ci.org/AFNetworking/AFNetworking)
|
||||
|
||||
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.
|
||||
|
||||
Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did!
|
||||
|
||||
## How To Get Started
|
||||
|
||||
- [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)
|
||||
- Check out the [documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at all of the APIs available in AFNetworking
|
||||
- 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
|
||||
|
||||
- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). (Tag 'afnetworking')
|
||||
- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking).
|
||||
- If you **found a bug**, _and can provide steps to reliably reproduce it_, open an issue.
|
||||
- If you **have a feature request**, open an issue.
|
||||
- If you **want to contribute**, submit a pull request.
|
||||
|
||||
### 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).
|
||||
|
||||
#### Podfile
|
||||
|
||||
```ruby
|
||||
platform :ios, '7.0'
|
||||
pod "AFNetworking", "~> 2.0"
|
||||
```
|
||||
|
||||
## Requirements
|
||||
|
||||
| AFNetworking Version | Minimum iOS Target | Minimum OS X Target | Notes |
|
||||
|:--------------------:|:---------------------------:|:----------------------------:|:-------------------------------------------------------------------------:|
|
||||
| 2.x | iOS 6 | OS X 10.8 | 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 | |
|
||||
| [0.10.x](https://github.com/AFNetworking/AFNetworking/tree/0.10.x) | iOS 4 | Mac OS X 10.6 | |
|
||||
|
||||
(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.
|
||||
|
||||
## Architecture
|
||||
|
||||
### NSURLConnection
|
||||
|
||||
- `AFURLConnectionOperation`
|
||||
- `AFHTTPRequestOperation`
|
||||
- `AFHTTPRequestOperationManager`
|
||||
|
||||
### NSURLSession _(iOS 7 / Mac OS X 10.9)_
|
||||
|
||||
- `AFURLSessionManager`
|
||||
- `AFHTTPSessionManager`
|
||||
|
||||
### Serialization
|
||||
|
||||
* `<AFURLRequestSerialization>`
|
||||
- `AFHTTPRequestSerializer`
|
||||
- `AFJSONRequestSerializer`
|
||||
- `AFPropertyListRequestSerializer`
|
||||
* `<AFURLResponseSerialization>`
|
||||
- `AFHTTPResponseSerializer`
|
||||
- `AFJSONResponseSerializer`
|
||||
- `AFXMLParserResponseSerializer`
|
||||
- `AFXMLDocumentResponseSerializer` _(Mac OS X)_
|
||||
- `AFPropertyListResponseSerializer`
|
||||
- `AFImageResponseSerializer`
|
||||
- `AFCompoundResponseSerializer`
|
||||
|
||||
### Additional Functionality
|
||||
|
||||
- `AFSecurityPolicy`
|
||||
- `AFNetworkReachabilityManager`
|
||||
|
||||
## 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` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
|
||||
|
||||
#### Creating a Download Task
|
||||
|
||||
```objective-c
|
||||
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
|
||||
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
|
||||
|
||||
NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
|
||||
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
|
||||
|
||||
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
|
||||
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
|
||||
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
|
||||
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
|
||||
NSLog(@"File downloaded to: %@", filePath);
|
||||
}];
|
||||
[downloadTask resume];
|
||||
```
|
||||
|
||||
#### Creating an Upload Task
|
||||
|
||||
```objective-c
|
||||
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
|
||||
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
|
||||
|
||||
NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
|
||||
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
|
||||
|
||||
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
|
||||
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
|
||||
if (error) {
|
||||
NSLog(@"Error: %@", error);
|
||||
} else {
|
||||
NSLog(@"Success: %@ %@", response, responseObject);
|
||||
}
|
||||
}];
|
||||
[uploadTask resume];
|
||||
```
|
||||
|
||||
#### Creating an Upload Task for a Multi-Part Request, with Progress
|
||||
|
||||
```objective-c
|
||||
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
|
||||
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
|
||||
} error:nil];
|
||||
|
||||
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
|
||||
NSProgress *progress = nil;
|
||||
|
||||
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
|
||||
if (error) {
|
||||
NSLog(@"Error: %@", error);
|
||||
} else {
|
||||
NSLog(@"%@ %@", response, responseObject);
|
||||
}
|
||||
}];
|
||||
|
||||
[uploadTask resume];
|
||||
```
|
||||
|
||||
#### Creating a Data Task
|
||||
|
||||
```objective-c
|
||||
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
|
||||
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
|
||||
|
||||
NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
|
||||
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
|
||||
|
||||
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
|
||||
if (error) {
|
||||
NSLog(@"Error: %@", error);
|
||||
} else {
|
||||
NSLog(@"%@ %@", response, responseObject);
|
||||
}
|
||||
}];
|
||||
[dataTask resume];
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Request Serialization
|
||||
|
||||
Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.
|
||||
|
||||
```objective-c
|
||||
NSString *URLString = @"http://example.com";
|
||||
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
|
||||
```
|
||||
|
||||
#### Query String Parameter Encoding
|
||||
|
||||
```objective-c
|
||||
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
|
||||
```
|
||||
|
||||
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
|
||||
|
||||
#### URL Form Parameter Encoding
|
||||
|
||||
```objective-c
|
||||
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
|
||||
```
|
||||
|
||||
POST http://example.com/
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
foo=bar&baz[]=1&baz[]=2&baz[]=3
|
||||
|
||||
#### JSON Parameter Encoding
|
||||
|
||||
```objective-c
|
||||
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
|
||||
```
|
||||
|
||||
POST http://example.com/
|
||||
Content-Type: application/json
|
||||
|
||||
{"foo": "bar", "baz": [1,2,3]}
|
||||
|
||||
---
|
||||
|
||||
### Network Reachability Manager
|
||||
|
||||
`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
|
||||
|
||||
* Do not use Reachability to determine if the original request should be sent.
|
||||
* You should try to send it.
|
||||
* You can use Reachability to determine when a request should be automatically retried.
|
||||
* Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something.
|
||||
* Network reachability is a useful tool for determining why a request might have failed.
|
||||
* After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out."
|
||||
|
||||
See also [WWDC 2012 session 706, "Networking Best Practices."](https://developer.apple.com/videos/play/wwdc2012-706/).
|
||||
|
||||
#### Shared Network Reachability
|
||||
|
||||
```objective-c
|
||||
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
|
||||
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
|
||||
}];
|
||||
|
||||
[[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
|
||||
|
||||
`AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
|
||||
|
||||
Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
|
||||
|
||||
#### Allowing Invalid SSL Certificates
|
||||
|
||||
```objective-c
|
||||
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
### Running Tests from the Command Line
|
||||
|
||||
Tests can also be run from the command line or within a continuous integration environment. The [`xcpretty`](https://github.com/supermarin/xcpretty) utility needs to be installed before running the tests from the command line:
|
||||
|
||||
$ gem install xcpretty
|
||||
|
||||
Once `xcpretty` is installed, you can execute the suite via `rake test`.
|
||||
|
||||
## Credits
|
||||
|
||||
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](https://en.wikipedia.org/wiki/Gowalla).
|
||||
|
||||
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/graphs/contributors).
|
||||
|
||||
### Security Disclosure
|
||||
|
||||
If you believe you have identified a security vulnerability with AFNetworking, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker.
|
||||
|
||||
## License
|
||||
|
||||
AFNetworking is released under the MIT license. See LICENSE for details.
|
||||
80
Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h
generated
Normal file
80
Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h
generated
Normal file
@ -0,0 +1,80 @@
|
||||
// AFNetworkActivityIndicatorManager.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
|
||||
|
||||
/**
|
||||
`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:
|
||||
|
||||
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
|
||||
|
||||
By setting `enabled` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself.
|
||||
|
||||
See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information:
|
||||
http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44
|
||||
*/
|
||||
NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.")
|
||||
@interface AFNetworkActivityIndicatorManager : NSObject
|
||||
|
||||
/**
|
||||
A Boolean value indicating whether the manager is enabled.
|
||||
|
||||
If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO.
|
||||
*/
|
||||
@property (nonatomic, assign, getter = isEnabled) BOOL enabled;
|
||||
|
||||
/**
|
||||
A Boolean value indicating whether the network activity indicator is currently displayed in the status bar.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible;
|
||||
|
||||
/**
|
||||
Returns the shared network activity indicator manager object for the system.
|
||||
|
||||
@return The systemwide network activity indicator manager.
|
||||
*/
|
||||
+ (instancetype)sharedManager;
|
||||
|
||||
/**
|
||||
Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator.
|
||||
*/
|
||||
- (void)incrementActivityCount;
|
||||
|
||||
/**
|
||||
Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator.
|
||||
*/
|
||||
- (void)decrementActivityCount;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
170
Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m
generated
Normal file
170
Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m
generated
Normal file
@ -0,0 +1,170 @@
|
||||
// AFNetworkActivityIndicatorManager.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 "AFNetworkActivityIndicatorManager.h"
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED)
|
||||
|
||||
#import "AFHTTPRequestOperation.h"
|
||||
|
||||
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
|
||||
#import "AFURLSessionManager.h"
|
||||
#endif
|
||||
|
||||
static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17;
|
||||
|
||||
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)]) {
|
||||
return [(NSURLSessionTask *)[notification object] originalRequest];
|
||||
}
|
||||
#endif
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
@interface AFNetworkActivityIndicatorManager ()
|
||||
@property (readwrite, nonatomic, assign) NSInteger activityCount;
|
||||
@property (readwrite, nonatomic, strong) NSTimer *activityIndicatorVisibilityTimer;
|
||||
@property (readonly, nonatomic, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
|
||||
|
||||
- (void)updateNetworkActivityIndicatorVisibility;
|
||||
- (void)updateNetworkActivityIndicatorVisibilityDelayed;
|
||||
@end
|
||||
|
||||
@implementation AFNetworkActivityIndicatorManager
|
||||
@dynamic networkActivityIndicatorVisible;
|
||||
|
||||
+ (instancetype)sharedManager {
|
||||
static AFNetworkActivityIndicatorManager *_sharedManager = nil;
|
||||
static dispatch_once_t oncePredicate;
|
||||
dispatch_once(&oncePredicate, ^{
|
||||
_sharedManager = [[self alloc] init];
|
||||
});
|
||||
|
||||
return _sharedManager;
|
||||
}
|
||||
|
||||
+ (NSSet *)keyPathsForValuesAffectingIsNetworkActivityIndicatorVisible {
|
||||
return [NSSet setWithObject:@"activityCount"];
|
||||
}
|
||||
|
||||
- (id)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
[[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(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil];
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil];
|
||||
#endif
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:self];
|
||||
|
||||
[_activityIndicatorVisibilityTimer invalidate];
|
||||
}
|
||||
|
||||
- (void)updateNetworkActivityIndicatorVisibilityDelayed {
|
||||
if (self.enabled) {
|
||||
// Delay hiding of activity indicator for a short interval, to avoid flickering
|
||||
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]];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)isNetworkActivityIndicatorVisible {
|
||||
return self.activityCount > 0;
|
||||
}
|
||||
|
||||
- (void)updateNetworkActivityIndicatorVisibility {
|
||||
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]];
|
||||
}
|
||||
|
||||
- (void)setActivityCount:(NSInteger)activityCount {
|
||||
@synchronized(self) {
|
||||
_activityCount = activityCount;
|
||||
}
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self updateNetworkActivityIndicatorVisibilityDelayed];
|
||||
});
|
||||
}
|
||||
|
||||
- (void)incrementActivityCount {
|
||||
[self willChangeValueForKey:@"activityCount"];
|
||||
@synchronized(self) {
|
||||
_activityCount++;
|
||||
}
|
||||
[self didChangeValueForKey:@"activityCount"];
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self updateNetworkActivityIndicatorVisibilityDelayed];
|
||||
});
|
||||
}
|
||||
|
||||
- (void)decrementActivityCount {
|
||||
[self willChangeValueForKey:@"activityCount"];
|
||||
@synchronized(self) {
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wgnu"
|
||||
_activityCount = MAX(_activityCount - 1, 0);
|
||||
#pragma clang diagnostic pop
|
||||
}
|
||||
[self didChangeValueForKey:@"activityCount"];
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self updateNetworkActivityIndicatorVisibilityDelayed];
|
||||
});
|
||||
}
|
||||
|
||||
- (void)networkRequestDidStart:(NSNotification *)notification {
|
||||
if ([AFNetworkRequestFromNotification(notification) URL]) {
|
||||
[self incrementActivityCount];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)networkRequestDidFinish:(NSNotification *)notification {
|
||||
if ([AFNetworkRequestFromNotification(notification) URL]) {
|
||||
[self decrementActivityCount];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
63
Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h
generated
Normal file
63
Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h
generated
Normal file
@ -0,0 +1,63 @@
|
||||
// UIActivityIndicatorView+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>
|
||||
|
||||
@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 request operation or session task.
|
||||
*/
|
||||
@interface UIActivityIndicatorView (AFNetworking)
|
||||
|
||||
///----------------------------------
|
||||
/// @name Animating for Session Tasks
|
||||
///----------------------------------
|
||||
|
||||
/**
|
||||
Binds the animating state to the state of the specified task.
|
||||
|
||||
@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;
|
||||
#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
|
||||
|
||||
#endif
|
||||
171
Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m
generated
Normal file
171
Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m
generated
Normal file
@ -0,0 +1,171 @@
|
||||
// UIActivityIndicatorView+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 "UIActivityIndicatorView+AFNetworking.h"
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
|
||||
#import "AFHTTPRequestOperation.h"
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
|
||||
#import "AFURLSessionManager.h"
|
||||
#endif
|
||||
|
||||
@interface AFActivityIndicatorViewNotificationObserver : NSObject
|
||||
@property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView;
|
||||
- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView;
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
|
||||
- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task;
|
||||
#endif
|
||||
- (void)setAnimatingWithStateOfOperation:(AFURLConnectionOperation *)operation;
|
||||
|
||||
@end
|
||||
|
||||
@implementation UIActivityIndicatorView (AFNetworking)
|
||||
|
||||
- (AFActivityIndicatorViewNotificationObserver *)af_notificationObserver {
|
||||
AFActivityIndicatorViewNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver));
|
||||
if (notificationObserver == nil) {
|
||||
notificationObserver = [[AFActivityIndicatorViewNotificationObserver alloc] initWithActivityIndicatorView:self];
|
||||
objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
return notificationObserver;
|
||||
}
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
|
||||
- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
|
||||
[[self af_notificationObserver] setAnimatingWithStateOfTask:task];
|
||||
}
|
||||
#endif
|
||||
|
||||
- (void)setAnimatingWithStateOfOperation:(AFURLConnectionOperation *)operation {
|
||||
[[self af_notificationObserver] setAnimatingWithStateOfOperation:operation];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation AFActivityIndicatorViewNotificationObserver
|
||||
|
||||
- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView
|
||||
{
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_activityIndicatorView = activityIndicatorView;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
|
||||
- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
|
||||
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
|
||||
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
|
||||
|
||||
if (task) {
|
||||
if (task.state != NSURLSessionTaskStateCompleted) {
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wreceiver-is-weak"
|
||||
#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak"
|
||||
if (task.state == NSURLSessionTaskStateRunning) {
|
||||
[self.activityIndicatorView startAnimating];
|
||||
} else {
|
||||
[self.activityIndicatorView stopAnimating];
|
||||
}
|
||||
#pragma clang diagnostic pop
|
||||
|
||||
[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:AFNetworkingTaskDidSuspendNotification object:task];
|
||||
}
|
||||
}
|
||||
}
|
||||
#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 -
|
||||
|
||||
- (void)af_startAnimating {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wreceiver-is-weak"
|
||||
[self.activityIndicatorView startAnimating];
|
||||
#pragma clang diagnostic pop
|
||||
});
|
||||
}
|
||||
|
||||
- (void)af_stopAnimating {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wreceiver-is-weak"
|
||||
[self.activityIndicatorView stopAnimating];
|
||||
#pragma clang diagnostic pop
|
||||
});
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)dealloc {
|
||||
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification 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
|
||||
|
||||
#endif
|
||||
99
Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.h
generated
Normal file
99
Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.h
generated
Normal file
@ -0,0 +1,99 @@
|
||||
// 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
|
||||
141
Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.m
generated
Normal file
141
Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.m
generated
Normal file
@ -0,0 +1,141 @@
|
||||
// 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
|
||||
186
Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h
generated
Normal file
186
Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h
generated
Normal file
@ -0,0 +1,186 @@
|
||||
// UIButton+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
|
||||
|
||||
@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.
|
||||
|
||||
@warning Compound values for control `state` (such as `UIControlStateHighlighted | UIControlStateDisabled`) are unsupported.
|
||||
*/
|
||||
@interface UIButton (AFNetworking)
|
||||
|
||||
///----------------------------
|
||||
/// @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 cache used for image loading.
|
||||
|
||||
@param imageCache The image cache.
|
||||
*/
|
||||
+ (void)setSharedImageCache:(__nullable id <AFImageCache>)imageCache;
|
||||
|
||||
///------------------------------------
|
||||
/// @name Accessing Response Serializer
|
||||
///------------------------------------
|
||||
|
||||
/**
|
||||
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
|
||||
*/
|
||||
@property (nonatomic, strong) id <AFURLResponseSerialization> imageResponseSerializer;
|
||||
|
||||
///--------------------
|
||||
/// @name Setting Image
|
||||
///--------------------
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
|
||||
|
||||
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||
|
||||
@param state The control state.
|
||||
@param url The URL used for the image request.
|
||||
*/
|
||||
- (void)setImageForState:(UIControlState)state
|
||||
withURL:(NSURL *)url;
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
|
||||
|
||||
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||
|
||||
@param state The control state.
|
||||
@param url The URL 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.
|
||||
*/
|
||||
- (void)setImageForState:(UIControlState)state
|
||||
withURL:(NSURL *)url
|
||||
placeholderImage:(nullable UIImage *)placeholderImage;
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
|
||||
|
||||
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||
|
||||
If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setImage:forState:` is applied.
|
||||
|
||||
@param state The control state.
|
||||
@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 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 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
|
||||
withURLRequest:(NSURLRequest *)urlRequest
|
||||
placeholderImage:(nullable UIImage *)placeholderImage
|
||||
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, UIImage *image))success
|
||||
failure:(nullable void (^)(NSError *error))failure;
|
||||
|
||||
|
||||
///-------------------------------
|
||||
/// @name Setting Background Image
|
||||
///-------------------------------
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous background image request for the receiver will be cancelled.
|
||||
|
||||
If the background image is cached locally, the background image is set immediately, otherwise the specified placeholder background image will be set immediately, and then the remote background image will be set once the request is finished.
|
||||
|
||||
@param state The control state.
|
||||
@param url The URL used for the background image request.
|
||||
*/
|
||||
- (void)setBackgroundImageForState:(UIControlState)state
|
||||
withURL:(NSURL *)url;
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
|
||||
|
||||
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||
|
||||
@param state The control state.
|
||||
@param url The URL used for the background 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.
|
||||
*/
|
||||
- (void)setBackgroundImageForState:(UIControlState)state
|
||||
withURL:(NSURL *)url
|
||||
placeholderImage:(nullable UIImage *)placeholderImage;
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
|
||||
|
||||
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||
|
||||
If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setBackgroundImage:forState:` is applied.
|
||||
|
||||
@param state The control state.
|
||||
@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 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 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
|
||||
withURLRequest:(NSURLRequest *)urlRequest
|
||||
placeholderImage:(nullable UIImage *)placeholderImage
|
||||
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, UIImage *image))success
|
||||
failure:(nullable void (^)(NSError *error))failure;
|
||||
|
||||
|
||||
///------------------------------
|
||||
/// @name Canceling Image Loading
|
||||
///------------------------------
|
||||
|
||||
/**
|
||||
Cancels any executing image operation for the specified control state of the receiver, if one exists.
|
||||
|
||||
@param state The control state.
|
||||
*/
|
||||
- (void)cancelImageRequestOperationForState:(UIControlState)state;
|
||||
|
||||
/**
|
||||
Cancels any executing background image operation for the specified control state of the receiver, if one exists.
|
||||
|
||||
@param state The control state.
|
||||
*/
|
||||
- (void)cancelBackgroundImageRequestOperationForState:(UIControlState)state;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
293
Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m
generated
Normal file
293
Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m
generated
Normal file
@ -0,0 +1,293 @@
|
||||
// UIButton+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 "UIButton+AFNetworking.h"
|
||||
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
|
||||
#import "AFURLResponseSerialization.h"
|
||||
#import "AFHTTPRequestOperation.h"
|
||||
|
||||
#import "UIImageView+AFNetworking.h"
|
||||
|
||||
@interface UIButton (_AFNetworking)
|
||||
@end
|
||||
|
||||
@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 -
|
||||
|
||||
static char AFImageRequestOperationNormal;
|
||||
static char AFImageRequestOperationHighlighted;
|
||||
static char AFImageRequestOperationSelected;
|
||||
static char AFImageRequestOperationDisabled;
|
||||
|
||||
static const char * af_imageRequestOperationKeyForState(UIControlState state) {
|
||||
switch (state) {
|
||||
case UIControlStateHighlighted:
|
||||
return &AFImageRequestOperationHighlighted;
|
||||
case UIControlStateSelected:
|
||||
return &AFImageRequestOperationSelected;
|
||||
case UIControlStateDisabled:
|
||||
return &AFImageRequestOperationDisabled;
|
||||
case UIControlStateNormal:
|
||||
default:
|
||||
return &AFImageRequestOperationNormal;
|
||||
}
|
||||
}
|
||||
|
||||
- (AFHTTPRequestOperation *)af_imageRequestOperationForState:(UIControlState)state {
|
||||
return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, af_imageRequestOperationKeyForState(state));
|
||||
}
|
||||
|
||||
- (void)af_setImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation
|
||||
forState:(UIControlState)state
|
||||
{
|
||||
objc_setAssociatedObject(self, af_imageRequestOperationKeyForState(state), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
static char AFBackgroundImageRequestOperationNormal;
|
||||
static char AFBackgroundImageRequestOperationHighlighted;
|
||||
static char AFBackgroundImageRequestOperationSelected;
|
||||
static char AFBackgroundImageRequestOperationDisabled;
|
||||
|
||||
static const char * af_backgroundImageRequestOperationKeyForState(UIControlState state) {
|
||||
switch (state) {
|
||||
case UIControlStateHighlighted:
|
||||
return &AFBackgroundImageRequestOperationHighlighted;
|
||||
case UIControlStateSelected:
|
||||
return &AFBackgroundImageRequestOperationSelected;
|
||||
case UIControlStateDisabled:
|
||||
return &AFBackgroundImageRequestOperationDisabled;
|
||||
case UIControlStateNormal:
|
||||
default:
|
||||
return &AFBackgroundImageRequestOperationNormal;
|
||||
}
|
||||
}
|
||||
|
||||
- (AFHTTPRequestOperation *)af_backgroundImageRequestOperationForState:(UIControlState)state {
|
||||
return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, af_backgroundImageRequestOperationKeyForState(state));
|
||||
}
|
||||
|
||||
- (void)af_setBackgroundImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation
|
||||
forState:(UIControlState)state
|
||||
{
|
||||
objc_setAssociatedObject(self, af_backgroundImageRequestOperationKeyForState(state), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation UIButton (AFNetworking)
|
||||
|
||||
+ (id <AFImageCache>)sharedImageCache {
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wgnu"
|
||||
return objc_getAssociatedObject(self, @selector(sharedImageCache)) ?: [UIImageView sharedImageCache];
|
||||
#pragma clang diagnostic pop
|
||||
}
|
||||
|
||||
+ (void)setSharedImageCache:(__nullable id <AFImageCache>)imageCache {
|
||||
objc_setAssociatedObject(self, @selector(sharedImageCache), imageCache, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (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 -
|
||||
|
||||
- (void)setImageForState:(UIControlState)state
|
||||
withURL:(NSURL *)url
|
||||
{
|
||||
[self setImageForState:state withURL:url placeholderImage:nil];
|
||||
}
|
||||
|
||||
- (void)setImageForState:(UIControlState)state
|
||||
withURL:(NSURL *)url
|
||||
placeholderImage:(UIImage *)placeholderImage
|
||||
{
|
||||
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
|
||||
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
|
||||
|
||||
[self setImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
|
||||
}
|
||||
|
||||
- (void)setImageForState:(UIControlState)state
|
||||
withURLRequest:(NSURLRequest *)urlRequest
|
||||
placeholderImage:(UIImage *)placeholderImage
|
||||
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, UIImage *image))success
|
||||
failure:(void (^)(NSError *error))failure
|
||||
{
|
||||
[self cancelImageRequestOperationForState:state];
|
||||
|
||||
UIImage *cachedImage = [[[self class] sharedImageCache] cachedImageForRequest:urlRequest];
|
||||
if (cachedImage) {
|
||||
if (success) {
|
||||
success(urlRequest, nil, cachedImage);
|
||||
} else {
|
||||
[self setImage:cachedImage forState:state];
|
||||
}
|
||||
|
||||
[self af_setImageRequestOperation:nil forState:state];
|
||||
} else {
|
||||
if (placeholderImage) {
|
||||
[self setImage:placeholderImage forState:state];
|
||||
}
|
||||
|
||||
__weak __typeof(self)weakSelf = self;
|
||||
AFHTTPRequestOperation *imageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
|
||||
imageRequestOperation.responseSerializer = self.imageResponseSerializer;
|
||||
[imageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
|
||||
__strong __typeof(weakSelf)strongSelf = weakSelf;
|
||||
if ([[urlRequest URL] isEqual:[operation.request URL]]) {
|
||||
if (success) {
|
||||
success(operation.request, operation.response, responseObject);
|
||||
} else if (responseObject) {
|
||||
[strongSelf setImage:responseObject forState:state];
|
||||
}
|
||||
}
|
||||
[[[strongSelf class] sharedImageCache] cacheImage:responseObject forRequest:urlRequest];
|
||||
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
|
||||
if ([[urlRequest URL] isEqual:[operation.request URL]]) {
|
||||
if (failure) {
|
||||
failure(error);
|
||||
}
|
||||
}
|
||||
}];
|
||||
|
||||
[self af_setImageRequestOperation:imageRequestOperation forState:state];
|
||||
[[[self class] af_sharedImageRequestOperationQueue] addOperation:imageRequestOperation];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)setBackgroundImageForState:(UIControlState)state
|
||||
withURL:(NSURL *)url
|
||||
{
|
||||
[self setBackgroundImageForState:state withURL:url placeholderImage:nil];
|
||||
}
|
||||
|
||||
- (void)setBackgroundImageForState:(UIControlState)state
|
||||
withURL:(NSURL *)url
|
||||
placeholderImage:(UIImage *)placeholderImage
|
||||
{
|
||||
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
|
||||
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
|
||||
|
||||
[self setBackgroundImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
|
||||
}
|
||||
|
||||
- (void)setBackgroundImageForState:(UIControlState)state
|
||||
withURLRequest:(NSURLRequest *)urlRequest
|
||||
placeholderImage:(UIImage *)placeholderImage
|
||||
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, UIImage *image))success
|
||||
failure:(void (^)(NSError *error))failure
|
||||
{
|
||||
[self cancelBackgroundImageRequestOperationForState:state];
|
||||
|
||||
UIImage *cachedImage = [[[self class] sharedImageCache] cachedImageForRequest:urlRequest];
|
||||
if (cachedImage) {
|
||||
if (success) {
|
||||
success(urlRequest, nil, cachedImage);
|
||||
} else {
|
||||
[self setBackgroundImage:cachedImage forState:state];
|
||||
}
|
||||
|
||||
[self af_setBackgroundImageRequestOperation:nil forState:state];
|
||||
} else {
|
||||
if (placeholderImage) {
|
||||
[self setBackgroundImage:placeholderImage forState:state];
|
||||
}
|
||||
|
||||
__weak __typeof(self)weakSelf = self;
|
||||
AFHTTPRequestOperation *backgroundImageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
|
||||
backgroundImageRequestOperation.responseSerializer = self.imageResponseSerializer;
|
||||
[backgroundImageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
|
||||
__strong __typeof(weakSelf)strongSelf = weakSelf;
|
||||
if ([[urlRequest URL] isEqual:[operation.request URL]]) {
|
||||
if (success) {
|
||||
success(operation.request, operation.response, responseObject);
|
||||
} else if (responseObject) {
|
||||
[strongSelf setBackgroundImage:responseObject forState:state];
|
||||
}
|
||||
}
|
||||
[[[strongSelf class] sharedImageCache] cacheImage:responseObject forRequest:urlRequest];
|
||||
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
|
||||
if ([[urlRequest URL] isEqual:[operation.request URL]]) {
|
||||
if (failure) {
|
||||
failure(error);
|
||||
}
|
||||
}
|
||||
}];
|
||||
|
||||
[self af_setBackgroundImageRequestOperation:backgroundImageRequestOperation forState:state];
|
||||
[[[self class] af_sharedImageRequestOperationQueue] addOperation:backgroundImageRequestOperation];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)cancelImageRequestOperationForState:(UIControlState)state {
|
||||
[[self af_imageRequestOperationForState:state] cancel];
|
||||
[self af_setImageRequestOperation:nil forState:state];
|
||||
}
|
||||
|
||||
- (void)cancelBackgroundImageRequestOperationForState:(UIControlState)state {
|
||||
[[self af_backgroundImageRequestOperationForState:state] cancel];
|
||||
[self af_setBackgroundImageRequestOperation:nil forState:state];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
35
Pods/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h
generated
Normal file
35
Pods/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h
generated
Normal file
@ -0,0 +1,35 @@
|
||||
//
|
||||
// UIImage+AFNetworking.h
|
||||
//
|
||||
//
|
||||
// Created by Paulo Ferreira on 08/07/15.
|
||||
//
|
||||
// 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.
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface UIImage (AFNetworking)
|
||||
|
||||
+ (UIImage*) safeImageWithData:(NSData*)data;
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
146
Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h
generated
Normal file
146
Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h
generated
Normal file
@ -0,0 +1,146 @@
|
||||
// UIImageView+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
|
||||
|
||||
@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.
|
||||
*/
|
||||
@interface UIImageView (AFNetworking)
|
||||
|
||||
///----------------------------
|
||||
/// @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 cache used for image loading.
|
||||
|
||||
@param imageCache The image cache.
|
||||
*/
|
||||
+ (void)setSharedImageCache:(__nullable id <AFImageCache>)imageCache;
|
||||
|
||||
///------------------------------------
|
||||
/// @name Accessing Response Serializer
|
||||
///------------------------------------
|
||||
|
||||
/**
|
||||
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
|
||||
*/
|
||||
@property (nonatomic, strong) id <AFURLResponseSerialization> imageResponseSerializer;
|
||||
|
||||
///--------------------
|
||||
/// @name Setting Image
|
||||
///--------------------
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
|
||||
|
||||
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||
|
||||
By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
|
||||
|
||||
@param url The URL used for the image request.
|
||||
*/
|
||||
- (void)setImageWithURL:(NSURL *)url;
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
|
||||
|
||||
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||
|
||||
By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
|
||||
|
||||
@param url The URL 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.
|
||||
*/
|
||||
- (void)setImageWithURL:(NSURL *)url
|
||||
placeholderImage:(nullable UIImage *)placeholderImage;
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL request, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
|
||||
|
||||
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||
|
||||
If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is applied.
|
||||
|
||||
@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 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 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
|
||||
placeholderImage:(nullable UIImage *)placeholderImage
|
||||
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, UIImage *image))success
|
||||
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Cancels any executing image operation for the receiver, if one exists.
|
||||
*/
|
||||
- (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
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
215
Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m
generated
Normal file
215
Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m
generated
Normal file
@ -0,0 +1,215 @@
|
||||
// UIImageView+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 "UIImageView+AFNetworking.h"
|
||||
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
|
||||
#import "AFHTTPRequestOperation.h"
|
||||
|
||||
@interface AFImageCache : NSCache <AFImageCache>
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@interface UIImageView (_AFNetworking)
|
||||
@property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFHTTPRequestOperation *af_imageRequestOperation;
|
||||
@end
|
||||
|
||||
@implementation UIImageView (_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;
|
||||
}
|
||||
|
||||
- (AFHTTPRequestOperation *)af_imageRequestOperation {
|
||||
return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, @selector(af_imageRequestOperation));
|
||||
}
|
||||
|
||||
- (void)af_setImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation {
|
||||
objc_setAssociatedObject(self, @selector(af_imageRequestOperation), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@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
|
||||
}
|
||||
|
||||
+ (void)setSharedImageCache:(__nullable id <AFImageCache>)imageCache {
|
||||
objc_setAssociatedObject(self, @selector(sharedImageCache), imageCache, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (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 -
|
||||
|
||||
- (void)setImageWithURL:(NSURL *)url {
|
||||
[self setImageWithURL:url placeholderImage:nil];
|
||||
}
|
||||
|
||||
- (void)setImageWithURL:(NSURL *)url
|
||||
placeholderImage:(UIImage *)placeholderImage
|
||||
{
|
||||
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
|
||||
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
|
||||
|
||||
[self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
|
||||
}
|
||||
|
||||
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
|
||||
placeholderImage:(UIImage *)placeholderImage
|
||||
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, UIImage *image))success
|
||||
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, NSError *error))failure
|
||||
{
|
||||
[self cancelImageRequestOperation];
|
||||
|
||||
UIImage *cachedImage = [[[self class] sharedImageCache] cachedImageForRequest:urlRequest];
|
||||
if (cachedImage) {
|
||||
if (success) {
|
||||
success(urlRequest, nil, cachedImage);
|
||||
} else {
|
||||
self.image = cachedImage;
|
||||
}
|
||||
|
||||
self.af_imageRequestOperation = nil;
|
||||
} else {
|
||||
if (placeholderImage) {
|
||||
self.image = placeholderImage;
|
||||
}
|
||||
|
||||
__weak __typeof(self)weakSelf = self;
|
||||
self.af_imageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
|
||||
self.af_imageRequestOperation.responseSerializer = self.imageResponseSerializer;
|
||||
[self.af_imageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
|
||||
__strong __typeof(weakSelf)strongSelf = weakSelf;
|
||||
if ([[urlRequest URL] isEqual:[strongSelf.af_imageRequestOperation.request URL]]) {
|
||||
if (success) {
|
||||
success(urlRequest, operation.response, responseObject);
|
||||
} else if (responseObject) {
|
||||
strongSelf.image = responseObject;
|
||||
}
|
||||
|
||||
if (operation == strongSelf.af_imageRequestOperation){
|
||||
strongSelf.af_imageRequestOperation = nil;
|
||||
}
|
||||
}
|
||||
|
||||
[[[strongSelf class] sharedImageCache] cacheImage:responseObject forRequest:urlRequest];
|
||||
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
|
||||
__strong __typeof(weakSelf)strongSelf = weakSelf;
|
||||
if ([[urlRequest URL] isEqual:[strongSelf.af_imageRequestOperation.request URL]]) {
|
||||
if (failure) {
|
||||
failure(urlRequest, operation.response, error);
|
||||
}
|
||||
|
||||
if (operation == strongSelf.af_imageRequestOperation){
|
||||
strongSelf.af_imageRequestOperation = nil;
|
||||
}
|
||||
}
|
||||
}];
|
||||
|
||||
[[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)cancelImageRequestOperation {
|
||||
[self.af_imageRequestOperation cancel];
|
||||
self.af_imageRequestOperation = nil;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
static inline NSString * AFImageCacheKeyFromURLRequest(NSURLRequest *request) {
|
||||
return [[request URL] absoluteString];
|
||||
}
|
||||
|
||||
@implementation AFImageCache
|
||||
|
||||
- (UIImage *)cachedImageForRequest:(NSURLRequest *)request {
|
||||
switch ([request cachePolicy]) {
|
||||
case NSURLRequestReloadIgnoringCacheData:
|
||||
case NSURLRequestReloadIgnoringLocalAndRemoteCacheData:
|
||||
return nil;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return [self objectForKey:AFImageCacheKeyFromURLRequest(request)];
|
||||
}
|
||||
|
||||
- (void)cacheImage:(UIImage *)image
|
||||
forRequest:(NSURLRequest *)request
|
||||
{
|
||||
if (image && request) {
|
||||
[self setObject:image forKey:AFImageCacheKeyFromURLRequest(request)];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
39
Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h
generated
Normal file
39
Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h
generated
Normal file
@ -0,0 +1,39 @@
|
||||
// UIKit+AFNetworking.h
|
||||
//
|
||||
// Copyright (c) 2013 AFNetworking (http://afnetworking.com/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#if TARGET_OS_IOS
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
#ifndef _UIKIT_AFNETWORKING_
|
||||
#define _UIKIT_AFNETWORKING_
|
||||
|
||||
#import "AFNetworkActivityIndicatorManager.h"
|
||||
|
||||
#import "UIActivityIndicatorView+AFNetworking.h"
|
||||
#import "UIAlertView+AFNetworking.h"
|
||||
#import "UIButton+AFNetworking.h"
|
||||
#import "UIImageView+AFNetworking.h"
|
||||
#import "UIProgressView+AFNetworking.h"
|
||||
#import "UIRefreshControl+AFNetworking.h"
|
||||
#import "UIWebView+AFNetworking.h"
|
||||
#endif /* _UIKIT_AFNETWORKING_ */
|
||||
#endif
|
||||
91
Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h
generated
Normal file
91
Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h
generated
Normal file
@ -0,0 +1,91 @@
|
||||
// UIProgressView+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 `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)
|
||||
|
||||
///------------------------------------
|
||||
/// @name Setting Session Task Progress
|
||||
///------------------------------------
|
||||
|
||||
/**
|
||||
Binds the progress to the upload progress of the specified session task.
|
||||
|
||||
@param task The session task.
|
||||
@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
|
||||
animated:(BOOL)animated;
|
||||
#endif
|
||||
|
||||
/**
|
||||
Binds the progress to the download progress of the specified session task.
|
||||
|
||||
@param task The session task.
|
||||
@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
|
||||
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
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
182
Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m
generated
Normal file
182
Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m
generated
Normal file
@ -0,0 +1,182 @@
|
||||
// UIProgressView+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 "UIProgressView+AFNetworking.h"
|
||||
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
|
||||
#import "AFURLConnectionOperation.h"
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
|
||||
#import "AFURLSessionManager.h"
|
||||
#endif
|
||||
|
||||
static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext;
|
||||
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 -
|
||||
|
||||
@implementation UIProgressView (AFNetworking)
|
||||
|
||||
- (BOOL)af_uploadProgressAnimated {
|
||||
return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_uploadProgressAnimated)) boolValue];
|
||||
}
|
||||
|
||||
- (void)af_setUploadProgressAnimated:(BOOL)animated {
|
||||
objc_setAssociatedObject(self, @selector(af_uploadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
- (BOOL)af_downloadProgressAnimated {
|
||||
return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_downloadProgressAnimated)) boolValue];
|
||||
}
|
||||
|
||||
- (void)af_setDownloadProgressAnimated:(BOOL)animated {
|
||||
objc_setAssociatedObject(self, @selector(af_downloadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
|
||||
- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
|
||||
animated:(BOOL)animated
|
||||
{
|
||||
[task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext];
|
||||
[task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext];
|
||||
|
||||
[self af_setUploadProgressAnimated:animated];
|
||||
}
|
||||
|
||||
- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
|
||||
animated:(BOOL)animated
|
||||
{
|
||||
[task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext];
|
||||
[task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext];
|
||||
|
||||
[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
|
||||
|
||||
- (void)observeValueForKeyPath:(NSString *)keyPath
|
||||
ofObject:(id)object
|
||||
change:(__unused NSDictionary *)change
|
||||
context:(void *)context
|
||||
{
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
|
||||
if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) {
|
||||
if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) {
|
||||
if ([object countOfBytesExpectedToSend] > 0) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self setProgress:[object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f) animated:self.af_uploadProgressAnimated];
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) {
|
||||
if ([object countOfBytesExpectedToReceive] > 0) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self setProgress:[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f) animated:self.af_downloadProgressAnimated];
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) {
|
||||
if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) {
|
||||
@try {
|
||||
[object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))];
|
||||
|
||||
if (context == AFTaskCountOfBytesSentContext) {
|
||||
[object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))];
|
||||
}
|
||||
|
||||
if (context == AFTaskCountOfBytesReceivedContext) {
|
||||
[object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))];
|
||||
}
|
||||
}
|
||||
@catch (NSException * __unused exception) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
68
Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h
generated
Normal file
68
Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h
generated
Normal file
@ -0,0 +1,68 @@
|
||||
// UIRefreshControl+AFNetworking.m
|
||||
//
|
||||
// Copyright (c) 2014 AFNetworking (http://afnetworking.com)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <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 `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)
|
||||
|
||||
///-----------------------------------
|
||||
/// @name Refreshing for Session Tasks
|
||||
///-----------------------------------
|
||||
|
||||
/**
|
||||
Binds the refreshing state to the state of the specified task.
|
||||
|
||||
@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;
|
||||
#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
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
166
Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m
generated
Normal file
166
Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m
generated
Normal file
@ -0,0 +1,166 @@
|
||||
// UIRefreshControl+AFNetworking.m
|
||||
//
|
||||
// Copyright (c) 2014 AFNetworking (http://afnetworking.com)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "UIRefreshControl+AFNetworking.h"
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
|
||||
#import "AFHTTPRequestOperation.h"
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
|
||||
#import "AFURLSessionManager.h"
|
||||
#endif
|
||||
|
||||
@interface AFRefreshControlNotificationObserver : NSObject
|
||||
@property (readonly, nonatomic, weak) UIRefreshControl *refreshControl;
|
||||
- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl;
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
|
||||
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task;
|
||||
#endif
|
||||
- (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation;
|
||||
|
||||
@end
|
||||
|
||||
@implementation UIRefreshControl (AFNetworking)
|
||||
|
||||
- (AFRefreshControlNotificationObserver *)af_notificationObserver {
|
||||
AFRefreshControlNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver));
|
||||
if (notificationObserver == nil) {
|
||||
notificationObserver = [[AFRefreshControlNotificationObserver alloc] initWithActivityRefreshControl:self];
|
||||
objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
return notificationObserver;
|
||||
}
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
|
||||
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task {
|
||||
[[self af_notificationObserver] setRefreshingWithStateOfTask:task];
|
||||
}
|
||||
#endif
|
||||
|
||||
- (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation {
|
||||
[[self af_notificationObserver] setRefreshingWithStateOfOperation:operation];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation AFRefreshControlNotificationObserver
|
||||
|
||||
- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl
|
||||
{
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_refreshControl = refreshControl;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
|
||||
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task {
|
||||
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
|
||||
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
|
||||
|
||||
if (task) {
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wreceiver-is-weak"
|
||||
#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak"
|
||||
if (task.state == NSURLSessionTaskStateRunning) {
|
||||
[self.refreshControl beginRefreshing];
|
||||
|
||||
[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:AFNetworkingTaskDidSuspendNotification object:task];
|
||||
} else {
|
||||
[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
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)af_beginRefreshing {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wreceiver-is-weak"
|
||||
[self.refreshControl beginRefreshing];
|
||||
#pragma clang diagnostic pop
|
||||
});
|
||||
}
|
||||
|
||||
- (void)af_endRefreshing {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wreceiver-is-weak"
|
||||
[self.refreshControl endRefreshing];
|
||||
#pragma clang diagnostic pop
|
||||
});
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)dealloc {
|
||||
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification 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
|
||||
|
||||
#endif
|
||||
86
Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h
generated
Normal file
86
Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h
generated
Normal file
@ -0,0 +1,86 @@
|
||||
// UIWebView+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 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.
|
||||
|
||||
@discussion When using these category methods, make sure to assign `delegate` for the web view, which implements `–webView:shouldStartLoadWithRequest:navigationType:` appropriately. This allows for tapped links to be loaded through AFNetworking, and can ensure that `canGoBack` & `canGoForward` update their values correctly.
|
||||
*/
|
||||
@interface UIWebView (AFNetworking)
|
||||
|
||||
/**
|
||||
The request serializer used to serialize requests made with the `-loadRequest:...` category methods. By default, this is an instance of `AFHTTPRequestSerializer`.
|
||||
*/
|
||||
@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.
|
||||
|
||||
@param request A URL request identifying the location of the content to load. This must not be `nil`.
|
||||
@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 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
|
||||
progress:(nullable void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress
|
||||
success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
|
||||
failure:(nullable void (^)(NSError *error))failure;
|
||||
|
||||
/**
|
||||
Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding.
|
||||
|
||||
@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 textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified.
|
||||
@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 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
|
||||
MIMEType:(nullable NSString *)MIMEType
|
||||
textEncodingName:(nullable NSString *)textEncodingName
|
||||
progress:(nullable void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress
|
||||
success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
|
||||
failure:(nullable void (^)(NSError *error))failure;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
159
Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m
generated
Normal file
159
Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m
generated
Normal file
@ -0,0 +1,159 @@
|
||||
// UIWebView+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 "UIWebView+AFNetworking.h"
|
||||
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
|
||||
#import "AFHTTPRequestOperation.h"
|
||||
#import "AFURLResponseSerialization.h"
|
||||
#import "AFURLRequestSerialization.h"
|
||||
|
||||
@interface UIWebView (_AFNetworking)
|
||||
@property (readwrite, nonatomic, strong, setter = af_setHTTPRequestOperation:) AFHTTPRequestOperation *af_HTTPRequestOperation;
|
||||
@end
|
||||
|
||||
@implementation UIWebView (_AFNetworking)
|
||||
|
||||
- (AFHTTPRequestOperation *)af_HTTPRequestOperation {
|
||||
return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, @selector(af_HTTPRequestOperation));
|
||||
}
|
||||
|
||||
- (void)af_setHTTPRequestOperation:(AFHTTPRequestOperation *)operation {
|
||||
objc_setAssociatedObject(self, @selector(af_HTTPRequestOperation), operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation UIWebView (AFNetworking)
|
||||
|
||||
- (AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
|
||||
static AFHTTPRequestSerializer <AFURLRequestSerialization> *_af_defaultRequestSerializer = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
_af_defaultRequestSerializer = [AFHTTPRequestSerializer serializer];
|
||||
});
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wgnu"
|
||||
return objc_getAssociatedObject(self, @selector(requestSerializer)) ?: _af_defaultRequestSerializer;
|
||||
#pragma clang diagnostic pop
|
||||
}
|
||||
|
||||
- (void)setRequestSerializer:(AFHTTPRequestSerializer<AFURLRequestSerialization> *)requestSerializer {
|
||||
objc_setAssociatedObject(self, @selector(requestSerializer), requestSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
- (AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
|
||||
static AFHTTPResponseSerializer <AFURLResponseSerialization> *_af_defaultResponseSerializer = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
_af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer];
|
||||
});
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wgnu"
|
||||
return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer;
|
||||
#pragma clang diagnostic pop
|
||||
}
|
||||
|
||||
- (void)setResponseSerializer:(AFHTTPResponseSerializer<AFURLResponseSerialization> *)responseSerializer {
|
||||
objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)loadRequest:(NSURLRequest *)request
|
||||
progress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress
|
||||
success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
|
||||
failure:(void (^)(NSError *error))failure
|
||||
{
|
||||
[self loadRequest:request MIMEType:nil textEncodingName:nil progress:progress success:^NSData *(NSHTTPURLResponse *response, NSData *data) {
|
||||
NSStringEncoding stringEncoding = NSUTF8StringEncoding;
|
||||
if (response.textEncodingName) {
|
||||
CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
|
||||
if (encoding != kCFStringEncodingInvalidId) {
|
||||
stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
|
||||
}
|
||||
}
|
||||
|
||||
NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding];
|
||||
if (success) {
|
||||
string = success(response, string);
|
||||
}
|
||||
|
||||
return [string dataUsingEncoding:stringEncoding];
|
||||
} failure:failure];
|
||||
}
|
||||
|
||||
- (void)loadRequest:(NSURLRequest *)request
|
||||
MIMEType:(NSString *)MIMEType
|
||||
textEncodingName:(NSString *)textEncodingName
|
||||
progress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress
|
||||
success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
|
||||
failure:(void (^)(NSError *error))failure
|
||||
{
|
||||
NSParameterAssert(request);
|
||||
|
||||
if (self.af_HTTPRequestOperation) {
|
||||
[self.af_HTTPRequestOperation cancel];
|
||||
}
|
||||
|
||||
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;
|
||||
[self.af_HTTPRequestOperation setDownloadProgressBlock:progress];
|
||||
[self.af_HTTPRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id __unused responseObject) {
|
||||
NSData *data = success ? success(operation.response, operation.responseData) : operation.responseData;
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wgnu"
|
||||
__strong __typeof(weakSelf) strongSelf = weakSelf;
|
||||
[strongSelf loadData:data MIMEType:(MIMEType ?: [operation.response MIMEType]) textEncodingName:(textEncodingName ?: [operation.response textEncodingName]) baseURL:[operation.response URL]];
|
||||
|
||||
if ([strongSelf.delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
|
||||
[strongSelf.delegate webViewDidFinishLoad:strongSelf];
|
||||
}
|
||||
|
||||
#pragma clang diagnostic pop
|
||||
} failure:^(AFHTTPRequestOperation * __unused operation, NSError *error) {
|
||||
if (failure) {
|
||||
failure(error);
|
||||
}
|
||||
}];
|
||||
|
||||
[self.af_HTTPRequestOperation start];
|
||||
|
||||
if ([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
|
||||
[self.delegate webViewDidStartLoad:self];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
74
Pods/AeroGearHttp/AeroGearHttp/AuthzModule.swift
generated
Normal file
74
Pods/AeroGearHttp/AeroGearHttp/AuthzModule.swift
generated
Normal file
@ -0,0 +1,74 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
The protocol that authorization modules must adhere to.
|
||||
*/
|
||||
public protocol AuthzModule {
|
||||
|
||||
/**
|
||||
Gateway to request authorization access.
|
||||
|
||||
:param: completionHandler A block object to be executed when the request operation finishes.
|
||||
*/
|
||||
func requestAccess(completionHandler: (AnyObject?, NSError?) -> Void)
|
||||
|
||||
/**
|
||||
Request an authorization code.
|
||||
|
||||
:param: completionHandler A block object to be executed when the request operation finishes.
|
||||
*/
|
||||
func requestAuthorizationCode(completionHandler: (AnyObject?, NSError?) -> Void)
|
||||
|
||||
/**
|
||||
Exchange an authorization code for an access token.
|
||||
|
||||
:param: completionHandler A block object to be executed when the request operation finishes.
|
||||
*/
|
||||
func exchangeAuthorizationCodeForAccessToken(code: String, completionHandler: (AnyObject?, NSError?) -> Void)
|
||||
|
||||
/**
|
||||
Request to refresh an access token.
|
||||
|
||||
:param: completionHandler A block object to be executed when the request operation finishes.
|
||||
*/
|
||||
func refreshAccessToken(completionHandler: (AnyObject?, NSError?) -> Void)
|
||||
|
||||
/**
|
||||
Request to revoke access.
|
||||
|
||||
:param: completionHandler A block object to be executed when the request operation finishes.
|
||||
*/
|
||||
func revokeAccess(completionHandler: (AnyObject?, NSError?) -> Void)
|
||||
|
||||
/**
|
||||
Return any authorization fields.
|
||||
|
||||
:returns: a dictionary filled with the authorization fields.
|
||||
*/
|
||||
func authorizationFields() -> [String: String]?
|
||||
|
||||
/**
|
||||
Returns a boolean indicating whether authorization has been granted.
|
||||
|
||||
:returns: true if authorized, false otherwise.
|
||||
*/
|
||||
func isAuthorized() -> Bool
|
||||
|
||||
}
|
||||
608
Pods/AeroGearHttp/AeroGearHttp/Http.swift
generated
Normal file
608
Pods/AeroGearHttp/AeroGearHttp/Http.swift
generated
Normal file
@ -0,0 +1,608 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
The HTTP method verb:
|
||||
|
||||
- GET: GET http verb
|
||||
- HEAD: HEAD http verb
|
||||
- DELETE: DELETE http verb
|
||||
- POST: POST http verb
|
||||
- PUT: PUT http verb
|
||||
*/
|
||||
public enum HttpMethod: String {
|
||||
case GET = "GET"
|
||||
case HEAD = "HEAD"
|
||||
case DELETE = "DELETE"
|
||||
case POST = "POST"
|
||||
case PUT = "PUT"
|
||||
}
|
||||
|
||||
/**
|
||||
The file request type:
|
||||
|
||||
- Download: Download request
|
||||
- Upload: Upload request
|
||||
*/
|
||||
enum FileRequestType {
|
||||
case Download(String?)
|
||||
case Upload(UploadType)
|
||||
}
|
||||
|
||||
/**
|
||||
The Upload enum type:
|
||||
|
||||
- Data: for a generic NSData object
|
||||
- File: for File passing the URL of the local file to upload
|
||||
- Stream: for a Stream request passing the actual NSInputStream
|
||||
*/
|
||||
enum UploadType {
|
||||
case Data(NSData)
|
||||
case File(NSURL)
|
||||
case Stream(NSInputStream)
|
||||
}
|
||||
|
||||
/**
|
||||
Error domain.
|
||||
**/
|
||||
public let HttpErrorDomain = "HttpDomain"
|
||||
/**
|
||||
Request error.
|
||||
**/
|
||||
public let NetworkingOperationFailingURLRequestErrorKey = "NetworkingOperationFailingURLRequestErrorKey"
|
||||
/**
|
||||
Response error.
|
||||
**/
|
||||
public let NetworkingOperationFailingURLResponseErrorKey = "NetworkingOperationFailingURLResponseErrorKey"
|
||||
|
||||
public typealias ProgressBlock = (Int64, Int64, Int64) -> Void
|
||||
public typealias CompletionBlock = (AnyObject?, NSError?) -> Void
|
||||
|
||||
/**
|
||||
Main class for performing HTTP operations across RESTful resources.
|
||||
*/
|
||||
public class Http {
|
||||
|
||||
var baseURL: String?
|
||||
var session: NSURLSession
|
||||
var requestSerializer: RequestSerializer
|
||||
var responseSerializer: ResponseSerializer
|
||||
public var authzModule: AuthzModule?
|
||||
|
||||
private var delegate: SessionDelegate
|
||||
|
||||
/**
|
||||
Initialize an HTTP object.
|
||||
|
||||
:param: baseURL the remote base URL of the application (optional).
|
||||
:param: sessionConfig the SessionConfiguration object (by default it uses a defaultSessionConfiguration).
|
||||
:param: requestSerializer the actual request serializer to use when performing requests.
|
||||
:param: responseSerializer the actual response serializer to use upon receiving a response.
|
||||
|
||||
:returns: the newly intitialized HTTP object
|
||||
*/
|
||||
public init(baseURL: String? = nil,
|
||||
sessionConfig: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(),
|
||||
requestSerializer: RequestSerializer = JsonRequestSerializer(),
|
||||
responseSerializer: ResponseSerializer = JsonResponseSerializer()) {
|
||||
self.baseURL = baseURL
|
||||
self.delegate = SessionDelegate()
|
||||
self.session = NSURLSession(configuration: sessionConfig, delegate: self.delegate, delegateQueue: NSOperationQueue.mainQueue())
|
||||
self.requestSerializer = requestSerializer
|
||||
self.responseSerializer = responseSerializer
|
||||
}
|
||||
|
||||
deinit {
|
||||
self.session.finishTasksAndInvalidate()
|
||||
}
|
||||
|
||||
/**
|
||||
Gateway to perform different http requests including multipart.
|
||||
|
||||
:param: url the url of the resource.
|
||||
:param: parameters the request parameters.
|
||||
:param: method the method to be used.
|
||||
:param: completionHandler A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
|
||||
*/
|
||||
public func request(method: HttpMethod, path: String, parameters: [String: AnyObject]? = nil, credential: NSURLCredential? = nil, responseSerializer: ResponseSerializer? = nil, completionHandler: CompletionBlock) {
|
||||
let block: () -> Void = {
|
||||
let finalOptURL = self.calculateURL(self.baseURL, url: path)
|
||||
guard let finalURL = finalOptURL else {
|
||||
let error = NSError(domain: "AeroGearHttp", code: 0, userInfo: [NSLocalizedDescriptionKey: "Malformed URL"])
|
||||
completionHandler(nil, error)
|
||||
return
|
||||
}
|
||||
|
||||
var request: NSURLRequest
|
||||
var task: NSURLSessionTask?
|
||||
var delegate: TaskDataDelegate
|
||||
// Merge headers
|
||||
let headers = merge(self.requestSerializer.headers, self.authzModule?.authorizationFields())
|
||||
|
||||
// care for multipart request is multipart data are set
|
||||
if (self.hasMultiPartData(parameters)) {
|
||||
request = self.requestSerializer.multipartRequest(finalURL, method: method, parameters: parameters, headers: headers)
|
||||
task = self.session.uploadTaskWithStreamedRequest(request)
|
||||
delegate = TaskUploadDelegate()
|
||||
} else {
|
||||
request = self.requestSerializer.request(finalURL, method: method, parameters: parameters, headers: headers)
|
||||
task = self.session.dataTaskWithRequest(request);
|
||||
delegate = TaskDataDelegate()
|
||||
}
|
||||
|
||||
delegate.completionHandler = completionHandler
|
||||
delegate.responseSerializer = responseSerializer == nil ? self.responseSerializer : responseSerializer
|
||||
delegate.credential = credential
|
||||
|
||||
self.delegate[task] = delegate
|
||||
if let task = task {task.resume()}
|
||||
}
|
||||
|
||||
// cater for authz and pre-authorize prior to performing request
|
||||
if (self.authzModule != nil) {
|
||||
self.authzModule?.requestAccess({ (response, error ) in
|
||||
// if there was an error during authz, no need to continue
|
||||
if (error != nil) {
|
||||
completionHandler(nil, error)
|
||||
return
|
||||
}
|
||||
// ..otherwise proceed normally
|
||||
block();
|
||||
})
|
||||
} else {
|
||||
block()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Gateway to perform different file requests either download or upload.
|
||||
|
||||
:param: url the url of the resource.
|
||||
:param: parameters the request parameters.
|
||||
:param: method the method to be used.
|
||||
:param: responseSerializer the actual response serializer to use upon receiving a response
|
||||
:param: type the file request type
|
||||
:param: progress a block that will be invoked to report progress during either download or upload.
|
||||
:param: completionHandler A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
|
||||
*/
|
||||
private func fileRequest(url: String, parameters: [String: AnyObject]? = nil, method: HttpMethod, credential: NSURLCredential? = nil, responseSerializer: ResponseSerializer? = nil, type: FileRequestType, progress: ProgressBlock?, completionHandler: CompletionBlock) {
|
||||
|
||||
let block: () -> Void = {
|
||||
let finalOptURL = self.calculateURL(self.baseURL, url: url)
|
||||
guard let finalURL = finalOptURL else {
|
||||
let error = NSError(domain: "AeroGearHttp", code: 0, userInfo: [NSLocalizedDescriptionKey: "Malformed URL"])
|
||||
completionHandler(nil, error)
|
||||
return
|
||||
}
|
||||
var request: NSURLRequest
|
||||
// Merge headers
|
||||
let headers = merge(self.requestSerializer.headers, self.authzModule?.authorizationFields())
|
||||
|
||||
// care for multipart request is multipart data are set
|
||||
if (self.hasMultiPartData(parameters)) {
|
||||
request = self.requestSerializer.multipartRequest(finalURL, method: method, parameters: parameters, headers: headers)
|
||||
} else {
|
||||
request = self.requestSerializer.request(finalURL, method: method, parameters: parameters, headers: headers)
|
||||
}
|
||||
|
||||
var task: NSURLSessionTask?
|
||||
|
||||
switch type {
|
||||
case .Download(let destinationDirectory):
|
||||
task = self.session.downloadTaskWithRequest(request)
|
||||
|
||||
let delegate = TaskDownloadDelegate()
|
||||
delegate.downloadProgress = progress
|
||||
delegate.destinationDirectory = destinationDirectory;
|
||||
delegate.completionHandler = completionHandler
|
||||
delegate.credential = credential
|
||||
delegate.responseSerializer = responseSerializer == nil ? self.responseSerializer : responseSerializer
|
||||
self.delegate[task] = delegate
|
||||
|
||||
case .Upload(let uploadType):
|
||||
switch uploadType {
|
||||
case .Data(let data):
|
||||
task = self.session.uploadTaskWithRequest(request, fromData: data)
|
||||
case .File(let url):
|
||||
task = self.session.uploadTaskWithRequest(request, fromFile: url)
|
||||
case .Stream(_):
|
||||
task = self.session.uploadTaskWithStreamedRequest(request)
|
||||
}
|
||||
|
||||
let delegate = TaskUploadDelegate()
|
||||
delegate.uploadProgress = progress
|
||||
delegate.completionHandler = completionHandler
|
||||
delegate.credential = credential
|
||||
delegate.responseSerializer = responseSerializer
|
||||
|
||||
self.delegate[task] = delegate
|
||||
}
|
||||
|
||||
if let task = task {task.resume()}
|
||||
}
|
||||
|
||||
// cater for authz and pre-authorize prior to performing request
|
||||
if (self.authzModule != nil) {
|
||||
self.authzModule?.requestAccess({ (response, error ) in
|
||||
// if there was an error during authz, no need to continue
|
||||
if (error != nil) {
|
||||
completionHandler(nil, error)
|
||||
return
|
||||
}
|
||||
// ..otherwise proceed normally
|
||||
block();
|
||||
})
|
||||
} else {
|
||||
block()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Request to download a file.
|
||||
|
||||
:param: url the URL of the downloadable resource.
|
||||
:param: destinationDirectory the destination directory where the file would be stored, if not specified. application's default '.Documents' directory would be used.
|
||||
:param: parameters the request parameters.
|
||||
:param: credential the credentials to use for basic/digest auth (Note: it is advised that HTTPS should be used by default).
|
||||
:param: method the method to be used, by default a .GET request.
|
||||
:param: progress a block that will be invoked to report progress during download.
|
||||
:param: completionHandler a block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
|
||||
*/
|
||||
public func download(url: String, destinationDirectory: String? = nil, parameters: [String: AnyObject]? = nil, credential: NSURLCredential? = nil, method: HttpMethod = .GET, progress: ProgressBlock?, completionHandler: CompletionBlock) {
|
||||
fileRequest(url, parameters: parameters, method: method, credential: credential, type: .Download(destinationDirectory), progress: progress, completionHandler: completionHandler)
|
||||
}
|
||||
|
||||
/**
|
||||
Request to upload a file using an NURL of a local file.
|
||||
|
||||
:param: url the URL to upload resource into.
|
||||
:param: file the URL of the local file to be uploaded.
|
||||
:param: parameters the request parameters.
|
||||
:param: credential the credentials to use for basic/digest auth (Note: it is advised that HTTPS should be used by default).
|
||||
:param: method the method to be used, by default a .POST request.
|
||||
:param: responseSerializer the actual response serializer to use upon receiving a response.
|
||||
:param: progress a block that will be invoked to report progress during upload.
|
||||
:param: completionHandler A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
|
||||
*/
|
||||
public func upload(url: String, file: NSURL, parameters: [String: AnyObject]? = nil, credential: NSURLCredential? = nil, method: HttpMethod = .POST, responseSerializer: ResponseSerializer? = nil, progress: ProgressBlock?, completionHandler: CompletionBlock) {
|
||||
fileRequest(url, parameters: parameters, method: method, credential: credential, responseSerializer: responseSerializer, type: .Upload(.File(file)), progress: progress, completionHandler: completionHandler)
|
||||
}
|
||||
|
||||
/**
|
||||
Request to upload a file using a raw NSData object.
|
||||
|
||||
:param: url the URL to upload resource into.
|
||||
:param: data the data to be uploaded.
|
||||
:param: parameters the request parameters.
|
||||
:param: credential the credentials to use for basic/digest auth (Note: it is advised that HTTPS should be used by default).
|
||||
:param: method the method to be used, by default a .POST request.
|
||||
:param: responseSerializer the actual response serializer to use upon receiving a response.
|
||||
:param: progress a block that will be invoked to report progress during upload.
|
||||
:param: completionHandler A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
|
||||
*/
|
||||
public func upload(url: String, data: NSData, parameters: [String: AnyObject]? = nil, credential: NSURLCredential? = nil, method: HttpMethod = .POST, responseSerializer: ResponseSerializer? = nil, progress: ProgressBlock?, completionHandler: CompletionBlock) {
|
||||
fileRequest(url, parameters: parameters, method: method, credential: credential, responseSerializer: responseSerializer, type: .Upload(.Data(data)), progress: progress, completionHandler: completionHandler)
|
||||
}
|
||||
|
||||
/**
|
||||
Request to upload a file using an NSInputStream object.
|
||||
|
||||
- parameter url: the URL to upload resource into.
|
||||
- parameter stream: the stream that will be used for uploading.
|
||||
- parameter parameters: the request parameters.
|
||||
- parameter credential: the credentials to use for basic/digest auth (Note: it is advised that HTTPS should be used by default).
|
||||
- parameter method: the method to be used, by default a .POST request.
|
||||
- parameter responseSerializer: the actual response serializer to use upon receiving a response.
|
||||
- parameter progress: a block that will be invoked to report progress during upload.
|
||||
- parameter completionHandler: A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
|
||||
*/
|
||||
public func upload(url: String, stream: NSInputStream, parameters: [String: AnyObject]? = nil, credential: NSURLCredential? = nil, method: HttpMethod = .POST, responseSerializer: ResponseSerializer? = nil, progress: ProgressBlock?, completionHandler: CompletionBlock) {
|
||||
fileRequest(url, parameters: parameters, method: method, credential: credential, responseSerializer: responseSerializer, type: .Upload(.Stream(stream)), progress: progress, completionHandler: completionHandler)
|
||||
}
|
||||
|
||||
|
||||
// MARK: Private API
|
||||
|
||||
// MARK: SessionDelegate
|
||||
class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
|
||||
|
||||
private var delegates: [Int: TaskDelegate]
|
||||
|
||||
private subscript(task: NSURLSessionTask?) -> TaskDelegate? {
|
||||
get {
|
||||
guard let task = task else {
|
||||
return nil
|
||||
}
|
||||
return self.delegates[task.taskIdentifier]
|
||||
}
|
||||
|
||||
set (newValue) {
|
||||
guard let task = task else {
|
||||
return
|
||||
}
|
||||
self.delegates[task.taskIdentifier] = newValue
|
||||
}
|
||||
}
|
||||
|
||||
required override init() {
|
||||
self.delegates = Dictionary()
|
||||
super.init()
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
|
||||
completionHandler(.PerformDefaultHandling, nil)
|
||||
}
|
||||
|
||||
func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
// MARK: NSURLSessionTaskDelegate
|
||||
|
||||
func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest?) -> Void) {
|
||||
|
||||
if let delegate = self[task] {
|
||||
delegate.URLSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request, completionHandler: completionHandler)
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
|
||||
|
||||
if let delegate = self[task] {
|
||||
delegate.URLSession(session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler)
|
||||
} else {
|
||||
self.URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: (NSInputStream?) -> Void) {
|
||||
if let delegate = self[task] {
|
||||
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
|
||||
if let delegate = self[task] as? TaskUploadDelegate {
|
||||
delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
|
||||
if let delegate = self[task] {
|
||||
delegate.URLSession(session, task: task, didCompleteWithError: error)
|
||||
|
||||
self[task] = nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: NSURLSessionDataDelegate
|
||||
|
||||
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
|
||||
completionHandler(.Allow)
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) {
|
||||
let downloadDelegate = TaskDownloadDelegate()
|
||||
self[downloadTask] = downloadDelegate
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
|
||||
if let delegate = self[dataTask] as? TaskDataDelegate {
|
||||
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: (NSCachedURLResponse?) -> Void) {
|
||||
completionHandler(proposedResponse)
|
||||
}
|
||||
|
||||
// MARK: NSURLSessionDownloadDelegate
|
||||
|
||||
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
|
||||
if let delegate = self[downloadTask] as? TaskDownloadDelegate {
|
||||
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
|
||||
if let delegate = self[downloadTask] as? TaskDownloadDelegate {
|
||||
delegate.URLSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
|
||||
if let delegate = self[downloadTask] as? TaskDownloadDelegate {
|
||||
delegate.URLSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: NSURLSessionTaskDelegate
|
||||
class TaskDelegate: NSObject, NSURLSessionTaskDelegate {
|
||||
|
||||
var data: NSData? { return nil }
|
||||
var completionHandler: ((AnyObject?, NSError?) -> Void)?
|
||||
var responseSerializer: ResponseSerializer?
|
||||
|
||||
var credential: NSURLCredential?
|
||||
|
||||
func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest?) -> Void) {
|
||||
|
||||
completionHandler(request)
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
|
||||
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
|
||||
var credential: NSURLCredential?
|
||||
|
||||
if challenge.previousFailureCount > 0 {
|
||||
disposition = .CancelAuthenticationChallenge
|
||||
} else {
|
||||
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
|
||||
|
||||
if credential != nil {
|
||||
disposition = .UseCredential
|
||||
}
|
||||
}
|
||||
|
||||
completionHandler(disposition, credential)
|
||||
}
|
||||
|
||||
|
||||
func URLSession(session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) {
|
||||
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
|
||||
if error != nil {
|
||||
completionHandler?(nil, error)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
let response = task.response as! NSHTTPURLResponse
|
||||
if let _ = task as? NSURLSessionDownloadTask {
|
||||
completionHandler?(response, error)
|
||||
return
|
||||
}
|
||||
|
||||
var responseObject: AnyObject? = nil
|
||||
do {
|
||||
if let data = data {
|
||||
try self.responseSerializer?.validateResponse(response, data)
|
||||
responseObject = self.responseSerializer?.response(data, response.statusCode)
|
||||
completionHandler?(responseObject, nil)
|
||||
}
|
||||
} catch let error as NSError {
|
||||
var userInfo = error.userInfo
|
||||
userInfo["StatusCode"] = response.statusCode
|
||||
let errorToRethrow = NSError(domain: error.domain, code: error.code, userInfo: userInfo)
|
||||
completionHandler?(responseObject, errorToRethrow)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: NSURLSessionDataDelegate
|
||||
class TaskDataDelegate: TaskDelegate, NSURLSessionDataDelegate {
|
||||
|
||||
private var mutableData: NSMutableData
|
||||
|
||||
override var data: NSData? {
|
||||
return self.mutableData
|
||||
}
|
||||
|
||||
override init() {
|
||||
self.mutableData = NSMutableData()
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
|
||||
completionHandler(.Allow)
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
|
||||
self.mutableData.appendData(data)
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: (NSCachedURLResponse?) -> Void) {
|
||||
let cachedResponse = proposedResponse
|
||||
completionHandler(cachedResponse)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: NSURLSessionDownloadDelegate
|
||||
class TaskDownloadDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
|
||||
|
||||
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
|
||||
var resumeData: NSData?
|
||||
var destinationDirectory: NSString?
|
||||
|
||||
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
|
||||
let filename = downloadTask.response?.suggestedFilename
|
||||
|
||||
// calculate final destination
|
||||
var finalDestination: NSURL
|
||||
if (destinationDirectory == nil) { // use 'default documents' directory if not set
|
||||
// use default documents directory
|
||||
let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
|
||||
finalDestination = documentsDirectory.URLByAppendingPathComponent(filename!)
|
||||
} else {
|
||||
// check that the directory exists
|
||||
let path = destinationDirectory?.stringByAppendingPathComponent(filename!)
|
||||
finalDestination = NSURL(fileURLWithPath: path!)
|
||||
}
|
||||
|
||||
do {
|
||||
try NSFileManager.defaultManager().moveItemAtURL(location, toURL: finalDestination)
|
||||
} catch _ {
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
|
||||
|
||||
self.downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: NSURLSessionTaskDelegate
|
||||
class TaskUploadDelegate: TaskDataDelegate {
|
||||
|
||||
var uploadProgress: ((Int64, Int64, Int64) -> Void)?
|
||||
|
||||
func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
|
||||
self.uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Utility methods
|
||||
public func calculateURL(baseURL: String?, var url: String) -> NSURL? {
|
||||
if (baseURL == nil || url.hasPrefix("http")) {
|
||||
return NSURL(string: url)!
|
||||
}
|
||||
|
||||
guard let finalURL = NSURL(string: baseURL!) else {return nil}
|
||||
if (url.hasPrefix("/")) {
|
||||
url = url.substringFromIndex(url.startIndex.advancedBy(1))
|
||||
}
|
||||
|
||||
return finalURL.URLByAppendingPathComponent(url);
|
||||
}
|
||||
|
||||
public func hasMultiPartData(parameters: [String: AnyObject]?) -> Bool {
|
||||
if (parameters == nil) {
|
||||
return false
|
||||
}
|
||||
|
||||
var isMultiPart = false
|
||||
for (_, value) in parameters! {
|
||||
if value is MultiPartData {
|
||||
isMultiPart = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return isMultiPart
|
||||
}
|
||||
}
|
||||
219
Pods/AeroGearHttp/AeroGearHttp/HttpRequestSerializer.swift
generated
Normal file
219
Pods/AeroGearHttp/AeroGearHttp/HttpRequestSerializer.swift
generated
Normal file
@ -0,0 +1,219 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
An HttpRequest serializer that handles form-encoded URL requess including multipart support.
|
||||
*/
|
||||
public class HttpRequestSerializer: RequestSerializer {
|
||||
/// The url that this request serializer is bound to.
|
||||
public var url: NSURL?
|
||||
/// Any headers that will be appended on the request.
|
||||
public var headers: [String: String]?
|
||||
/// The String encoding to be used.
|
||||
public var stringEncoding: NSNumber
|
||||
/// The cache policy.
|
||||
public var cachePolicy: NSURLRequestCachePolicy
|
||||
/// The timeout interval.
|
||||
public var timeoutInterval: NSTimeInterval
|
||||
|
||||
/// Defualt initializer.
|
||||
public init() {
|
||||
self.stringEncoding = NSUTF8StringEncoding
|
||||
self.timeoutInterval = 60
|
||||
self.cachePolicy = .UseProtocolCachePolicy
|
||||
}
|
||||
|
||||
/**
|
||||
Build an request using the specified params passed in.
|
||||
|
||||
:param: url the url of the resource.
|
||||
:param: method the method to be used.
|
||||
:param: parameters the request parameters.
|
||||
:param: headers any headers to be used on this request.
|
||||
|
||||
:returns: the URLRequest object.
|
||||
*/
|
||||
public func request(url: NSURL, method: HttpMethod, parameters: [String: AnyObject]?, headers: [String: String]? = nil) -> NSURLRequest {
|
||||
let request = NSMutableURLRequest(URL: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval)
|
||||
request.HTTPMethod = method.rawValue
|
||||
|
||||
// apply headers to new request
|
||||
if(headers != nil) {
|
||||
for (key,val) in headers! {
|
||||
request.addValue(val, forHTTPHeaderField: key)
|
||||
}
|
||||
}
|
||||
|
||||
if method == HttpMethod.GET || method == HttpMethod.HEAD || method == HttpMethod.DELETE {
|
||||
let paramSeparator = request.URL?.query != nil ? "&" : "?"
|
||||
var newUrl:String
|
||||
if (request.URL?.absoluteString != nil && parameters != nil) {
|
||||
let queryString = self.stringFromParameters(parameters!)
|
||||
newUrl = "\(request.URL!.absoluteString)\(paramSeparator)\(queryString)"
|
||||
request.URL = NSURL(string: newUrl)!
|
||||
}
|
||||
|
||||
} else {
|
||||
// set type
|
||||
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
|
||||
// set body
|
||||
if (parameters != nil) {
|
||||
let body = self.stringFromParameters(parameters!).dataUsingEncoding(NSUTF8StringEncoding)
|
||||
request.setValue("\(body?.length)", forHTTPHeaderField: "Content-Length")
|
||||
request.HTTPBody = body
|
||||
}
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
/**
|
||||
Build an multipart request using the specified params passed in.
|
||||
|
||||
:param: url the url of the resource.
|
||||
:param: method the method to be used.
|
||||
:param: parameters the request parameters.
|
||||
:param: headers any headers to be used on this request.
|
||||
|
||||
:returns: the URLRequest object
|
||||
*/
|
||||
public func multipartRequest(url: NSURL, method: HttpMethod, parameters: [String: AnyObject]?, headers: [String: String]? = nil) -> NSURLRequest {
|
||||
let request = NSMutableURLRequest(URL: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval)
|
||||
request.HTTPMethod = method.rawValue
|
||||
|
||||
// apply headers to new request
|
||||
if(headers != nil) {
|
||||
for (key,val) in headers! {
|
||||
request.addValue(val, forHTTPHeaderField: key)
|
||||
}
|
||||
}
|
||||
|
||||
let boundary = "AG-boundary-\(arc4random())-\(arc4random())"
|
||||
let type = "multipart/form-data; boundary=\(boundary)"
|
||||
let body = self.multiPartBodyFromParams(parameters!, boundary: boundary)
|
||||
|
||||
request.setValue(type, forHTTPHeaderField: "Content-Type")
|
||||
request.setValue("\(body.length)", forHTTPHeaderField: "Content-Length")
|
||||
request.HTTPBody = body
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
public func stringFromParameters(parameters: [String: AnyObject]) -> String {
|
||||
let parametersArray = serialize((nil, parameters)).map({(tuple) in
|
||||
return self.stringValue(tuple)
|
||||
})
|
||||
return parametersArray.joinWithSeparator("&")
|
||||
// return "&".join(serialize((nil, parameters)).map({(tuple) in
|
||||
// return self.stringValue(tuple)
|
||||
// }))
|
||||
}
|
||||
|
||||
public func serialize(tuple: (String?, AnyObject)) -> [(String?, AnyObject)] {
|
||||
var collect:[(String?, AnyObject)] = []
|
||||
if let array = tuple.1 as? [AnyObject] {
|
||||
for nestedValue : AnyObject in array {
|
||||
let label: String = tuple.0!
|
||||
let myTuple:(String?, AnyObject) = (label + "[]", nestedValue)
|
||||
collect.appendContentsOf(self.serialize(myTuple))
|
||||
}
|
||||
} else if let dict = tuple.1 as? [String: AnyObject] {
|
||||
for (nestedKey, nestedObject) in dict {
|
||||
let newKey = tuple.0 != nil ? "\(tuple.0!)[\(nestedKey)]" : nestedKey
|
||||
let myTuple:(String?, AnyObject) = (newKey, nestedObject)
|
||||
collect.appendContentsOf(self.serialize(myTuple))
|
||||
}
|
||||
} else {
|
||||
collect.append((tuple.0, tuple.1))
|
||||
}
|
||||
return collect
|
||||
}
|
||||
|
||||
public func stringValue(tuple: (String?, AnyObject)) -> String {
|
||||
var val = ""
|
||||
if let str = tuple.1 as? String {
|
||||
val = str
|
||||
} else if tuple.1.description != nil {
|
||||
val = tuple.1.description
|
||||
}
|
||||
|
||||
if tuple.0 == nil {
|
||||
return val.urlEncode()
|
||||
}
|
||||
|
||||
return "\(tuple.0!.urlEncode())=\(val.urlEncode())"
|
||||
}
|
||||
|
||||
public func multiPartBodyFromParams(parameters: [String: AnyObject], boundary: String) -> NSData {
|
||||
let data = NSMutableData()
|
||||
|
||||
let prefixData = "--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)
|
||||
let seperData = "\r\n".dataUsingEncoding(NSUTF8StringEncoding)
|
||||
|
||||
for (key, value) in parameters {
|
||||
var sectionData: NSData?
|
||||
var sectionType: String?
|
||||
var sectionFilename = ""
|
||||
|
||||
if value is MultiPartData {
|
||||
let multiData = value as! MultiPartData
|
||||
sectionData = multiData.data
|
||||
sectionType = multiData.mimeType
|
||||
sectionFilename = " filename=\"\(multiData.filename)\""
|
||||
} else {
|
||||
sectionData = "\(value)".dataUsingEncoding(NSUTF8StringEncoding)
|
||||
}
|
||||
|
||||
data.appendData(prefixData!)
|
||||
|
||||
let sectionDisposition = "Content-Disposition: form-data; name=\"\(key)\";\(sectionFilename)\r\n".dataUsingEncoding(NSUTF8StringEncoding)
|
||||
data.appendData(sectionDisposition!)
|
||||
|
||||
if let type = sectionType {
|
||||
let contentType = "Content-Type: \(type)\r\n".dataUsingEncoding(NSUTF8StringEncoding)
|
||||
data.appendData(contentType!)
|
||||
}
|
||||
|
||||
// append data
|
||||
data.appendData(seperData!)
|
||||
data.appendData(sectionData!)
|
||||
data.appendData(seperData!)
|
||||
}
|
||||
|
||||
data.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
public func hasMultiPartData(parameters: [String: AnyObject]?) -> Bool {
|
||||
if (parameters == nil) {
|
||||
return false
|
||||
}
|
||||
|
||||
var isMultiPart = false
|
||||
for (_, value) in parameters! {
|
||||
if value is MultiPartData {
|
||||
isMultiPart = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return isMultiPart
|
||||
}
|
||||
}
|
||||
68
Pods/AeroGearHttp/AeroGearHttp/JsonRequestSerializer.swift
generated
Normal file
68
Pods/AeroGearHttp/AeroGearHttp/JsonRequestSerializer.swift
generated
Normal file
@ -0,0 +1,68 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
A request serializer to JSON objects/
|
||||
*/
|
||||
public class JsonRequestSerializer: HttpRequestSerializer {
|
||||
/**
|
||||
Build an request using the specified params passed in.
|
||||
|
||||
:param: url the url of the resource.
|
||||
:param: method the method to be used.
|
||||
:param: parameters the request parameters.
|
||||
:param: headers any headers to be used on this request.
|
||||
|
||||
:returns: the URLRequest object.
|
||||
*/
|
||||
public override func request(url: NSURL, method: HttpMethod, parameters: [String: AnyObject]?, headers: [String: String]? = nil) -> NSURLRequest {
|
||||
if method == HttpMethod.GET || method == HttpMethod.HEAD || method == HttpMethod.DELETE {
|
||||
return super.request(url, method: method, parameters: parameters, headers: headers)
|
||||
} else {
|
||||
let request = NSMutableURLRequest(URL: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval)
|
||||
request.HTTPMethod = method.rawValue
|
||||
|
||||
// set type
|
||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
// set body
|
||||
if (parameters != nil) {
|
||||
var body: NSData?
|
||||
do {
|
||||
body = try NSJSONSerialization.dataWithJSONObject(parameters!, options: [])
|
||||
} catch _ {
|
||||
body = nil
|
||||
}
|
||||
// set body
|
||||
if (body != nil) {
|
||||
request.setValue("\(body?.length)", forHTTPHeaderField: "Content-Length")
|
||||
request.HTTPBody = body
|
||||
}
|
||||
}
|
||||
|
||||
// apply headers to new request
|
||||
if(headers != nil) {
|
||||
for (key,val) in headers! {
|
||||
request.addValue(val, forHTTPHeaderField: key)
|
||||
}
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
}
|
||||
}
|
||||
84
Pods/AeroGearHttp/AeroGearHttp/JsonResponseSerializer.swift
generated
Normal file
84
Pods/AeroGearHttp/AeroGearHttp/JsonResponseSerializer.swift
generated
Normal file
@ -0,0 +1,84 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
A response deserializer to JSON objects.
|
||||
*/
|
||||
public class JsonResponseSerializer : ResponseSerializer {
|
||||
|
||||
/**
|
||||
Validate the response received. throw an error is the response is not va;id.
|
||||
|
||||
:returns: either true or false if the response is valid for this particular serializer.
|
||||
*/
|
||||
public var validateResponse: (NSURLResponse!, NSData) throws -> Void = { (response: NSURLResponse!, data: NSData) -> Void in
|
||||
var error: NSError! = NSError(domain: "AeroGearHttp", code: 0, userInfo: nil)
|
||||
let httpResponse = response as! NSHTTPURLResponse
|
||||
let dataAsJson: [String: AnyObject]?
|
||||
|
||||
// validate JSON
|
||||
do {
|
||||
dataAsJson = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as? [String: AnyObject]
|
||||
} catch _ {
|
||||
let userInfo = [NSLocalizedDescriptionKey: "Invalid response received, can't parse JSON" as NSString,
|
||||
NetworkingOperationFailingURLResponseErrorKey: response]
|
||||
let customError = NSError(domain: HttpResponseSerializationErrorDomain, code: NSURLErrorBadServerResponse, userInfo: userInfo)
|
||||
throw customError;
|
||||
}
|
||||
|
||||
if !(httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
|
||||
var userInfo = [NSLocalizedDescriptionKey: NSHTTPURLResponse.localizedStringForStatusCode(httpResponse.statusCode),
|
||||
NetworkingOperationFailingURLResponseErrorKey: response]
|
||||
if let dataAsJson = dataAsJson {
|
||||
userInfo["CustomData"] = dataAsJson
|
||||
}
|
||||
error = NSError(domain: HttpResponseSerializationErrorDomain, code: httpResponse.statusCode, userInfo: userInfo)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Deserialize the response received.
|
||||
|
||||
:returns: the serialized response
|
||||
*/
|
||||
public var response: (NSData, Int) -> AnyObject? = { (data: NSData, Int) -> AnyObject? in
|
||||
do {
|
||||
return try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
|
||||
} catch _ {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
public init() {
|
||||
}
|
||||
|
||||
public init(validateResponse: (NSURLResponse!, NSData) throws -> Void, response: (NSData, Int) -> AnyObject?) {
|
||||
self.validateResponse = validateResponse
|
||||
self.response = response
|
||||
}
|
||||
|
||||
public init(validateResponse: (NSURLResponse!, NSData) throws -> Void) {
|
||||
self.validateResponse = validateResponse
|
||||
}
|
||||
|
||||
public init(response: (NSData, Int) -> AnyObject?) {
|
||||
self.response = response
|
||||
}
|
||||
}
|
||||
66
Pods/AeroGearHttp/AeroGearHttp/MultiPartData.swift
generated
Normal file
66
Pods/AeroGearHttp/AeroGearHttp/MultiPartData.swift
generated
Normal file
@ -0,0 +1,66 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Represents a multipart object containing a file plus metadata to be processed during upload.
|
||||
*/
|
||||
public class MultiPartData {
|
||||
|
||||
/// The 'name' to be used on the request.
|
||||
public var name: String
|
||||
/// The 'filename' to be used on the request.
|
||||
public var filename: String
|
||||
/// The 'MIME type' to be used on the request.
|
||||
public var mimeType: String
|
||||
/// The actual data to be sent.
|
||||
public var data: NSData
|
||||
|
||||
/**
|
||||
Initialize a multipart object using an NSURL and a corresponding MIME type.
|
||||
|
||||
:param: url the url of the local file.
|
||||
:param: mimeType the MIME type.
|
||||
|
||||
:returns: the newly created multipart data.
|
||||
*/
|
||||
public init(url: NSURL, mimeType: String) {
|
||||
self.name = url.lastPathComponent!
|
||||
self.filename = url.lastPathComponent!
|
||||
self.mimeType = mimeType;
|
||||
|
||||
self.data = NSData(contentsOfURL: url)!
|
||||
}
|
||||
|
||||
/**
|
||||
Initialize a multipart object using an NSData plus metadata.
|
||||
|
||||
:param: data the actual data to be uploaded.
|
||||
:param: name the 'name' to be used on the request.
|
||||
:param: filename the 'filename' to be used on the request.
|
||||
:param: mimeType the 'MIME type' to be used on the request.
|
||||
|
||||
:returns: the newly created multipart data.
|
||||
*/
|
||||
public init(data: NSData, name: String, filename: String, mimeType: String) {
|
||||
self.data = data;
|
||||
self.name = name;
|
||||
self.filename = filename;
|
||||
self.mimeType = mimeType;
|
||||
}
|
||||
}
|
||||
59
Pods/AeroGearHttp/AeroGearHttp/RequestSerializer.swift
generated
Normal file
59
Pods/AeroGearHttp/AeroGearHttp/RequestSerializer.swift
generated
Normal file
@ -0,0 +1,59 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
The protocol that request serializers must adhere to.
|
||||
*/
|
||||
public protocol RequestSerializer {
|
||||
|
||||
/// The url that this request serializer is bound to.
|
||||
var url: NSURL? { get set }
|
||||
/// Any headers that will be appended on the request.
|
||||
var headers: [String: String]? { get set }
|
||||
/// The String encoding to be used.
|
||||
var stringEncoding: NSNumber { get }
|
||||
/// The cache policy.
|
||||
var cachePolicy: NSURLRequestCachePolicy { get }
|
||||
/// The timeout interval.
|
||||
var timeoutInterval: NSTimeInterval { get set }
|
||||
|
||||
/**
|
||||
Build an request using the specified params passed in.
|
||||
|
||||
:param: url the url of the resource.
|
||||
:param: method the method to be used.
|
||||
:param: parameters the request parameters.
|
||||
:param: headers any headers to be used on this request.
|
||||
|
||||
:returns: the URLRequest object.
|
||||
*/
|
||||
func request(url: NSURL, method: HttpMethod, parameters: [String: AnyObject]?, headers: [String: String]?) -> NSURLRequest
|
||||
|
||||
/**
|
||||
Build an multipart request using the specified params passed in.
|
||||
|
||||
:param: url the url of the resource.
|
||||
:param: method the method to be used.
|
||||
:param: parameters the request parameters.
|
||||
:param: headers any headers to be used on this request.
|
||||
|
||||
:returns: the URLRequest object
|
||||
*/
|
||||
func multipartRequest(url: NSURL, method: HttpMethod, parameters: [String: AnyObject]?, headers: [String: String]?) -> NSURLRequest
|
||||
}
|
||||
43
Pods/AeroGearHttp/AeroGearHttp/ResponseSerializer.swift
generated
Normal file
43
Pods/AeroGearHttp/AeroGearHttp/ResponseSerializer.swift
generated
Normal file
@ -0,0 +1,43 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Error domain for serializers.
|
||||
*/
|
||||
public let HttpResponseSerializationErrorDomain = "ResponseSerializerDomain"
|
||||
|
||||
/**
|
||||
The protocol that response serializers must adhere to.
|
||||
*/
|
||||
public protocol ResponseSerializer {
|
||||
|
||||
/**
|
||||
Deserialize the response received.
|
||||
|
||||
:returns: the serialized response
|
||||
*/
|
||||
var response: (NSData, Int) -> AnyObject? {get set}
|
||||
|
||||
/**
|
||||
Validate the response received. This is a cutomizable closure variable.
|
||||
|
||||
:returns: either true or false if the response is valid for this particular serializer.
|
||||
*/
|
||||
var validateResponse: (NSURLResponse!, NSData) throws -> Void {get set}
|
||||
}
|
||||
70
Pods/AeroGearHttp/AeroGearHttp/StringResponseSerializer.swift
generated
Normal file
70
Pods/AeroGearHttp/AeroGearHttp/StringResponseSerializer.swift
generated
Normal file
@ -0,0 +1,70 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
A response deserializer to a generic String object.
|
||||
*/
|
||||
public class StringResponseSerializer : ResponseSerializer {
|
||||
/**
|
||||
Deserialize the response received.
|
||||
|
||||
:returns: the serialized response
|
||||
*/
|
||||
public var response: (NSData, Int) -> AnyObject? = {(data: NSData, status: Int) -> (AnyObject?) in
|
||||
return NSString(data: data, encoding:NSUTF8StringEncoding)
|
||||
}
|
||||
|
||||
/**
|
||||
Validate the response received.
|
||||
|
||||
:returns: either true or false if the response is valid for this particular serializer.
|
||||
*/
|
||||
public var validateResponse: (NSURLResponse!, NSData) throws -> Void = { (response: NSURLResponse!, data: NSData) throws in
|
||||
var error: NSError! = NSError(domain: "Migrator", code: 0, userInfo: nil)
|
||||
let httpResponse = response as! NSHTTPURLResponse
|
||||
|
||||
if !(httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
|
||||
let userInfo = [
|
||||
NSLocalizedDescriptionKey: NSHTTPURLResponse.localizedStringForStatusCode(httpResponse.statusCode),
|
||||
NetworkingOperationFailingURLResponseErrorKey: response]
|
||||
|
||||
if (true) {
|
||||
error = NSError(domain: HttpResponseSerializationErrorDomain, code: httpResponse.statusCode, userInfo: userInfo)
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
public init() {
|
||||
}
|
||||
|
||||
public init(validateResponse: (NSURLResponse!, NSData) throws -> Void, response: (NSData, Int) -> AnyObject?) {
|
||||
self.validateResponse = validateResponse
|
||||
self.response = response
|
||||
}
|
||||
|
||||
public init(validateResponse: (NSURLResponse!, NSData) throws -> Void) {
|
||||
self.validateResponse = validateResponse
|
||||
}
|
||||
|
||||
public init(response: (NSData, Int) -> AnyObject?) {
|
||||
self.response = response
|
||||
}
|
||||
}
|
||||
49
Pods/AeroGearHttp/AeroGearHttp/Utils.swift
generated
Normal file
49
Pods/AeroGearHttp/AeroGearHttp/Utils.swift
generated
Normal file
@ -0,0 +1,49 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Handy extensions and utilities.
|
||||
*/
|
||||
extension String {
|
||||
|
||||
public func urlEncode() -> String {
|
||||
let encodedURL = CFURLCreateStringByAddingPercentEscapes(nil,
|
||||
self as NSString,
|
||||
nil,
|
||||
"!@#$%&*'();:=+,/?[]",
|
||||
CFStringBuiltInEncodings.UTF8.rawValue)
|
||||
return encodedURL as String
|
||||
}
|
||||
}
|
||||
|
||||
public func merge(one: [String: String]?, _ two: [String:String]?) -> [String: String]? {
|
||||
var dict: [String: String]?
|
||||
if let one = one {
|
||||
dict = one
|
||||
if let two = two {
|
||||
for (key, value) in two {
|
||||
dict![key] = value
|
||||
}
|
||||
}
|
||||
} else {
|
||||
dict = two
|
||||
}
|
||||
return dict
|
||||
}
|
||||
|
||||
202
Pods/AeroGearHttp/LICENSE.txt
generated
Normal file
202
Pods/AeroGearHttp/LICENSE.txt
generated
Normal file
@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
160
Pods/AeroGearHttp/README.md
generated
Normal file
160
Pods/AeroGearHttp/README.md
generated
Normal file
@ -0,0 +1,160 @@
|
||||
# aerogear-ios-http [](https://travis-ci.org/aerogear/aerogear-ios-http)
|
||||
|
||||
> This module currently build with Xcode 7.2 and supports iOS8, iOS9.
|
||||
|
||||
Thin layer to take care of your http requests working with NSURLSession.
|
||||
Taking care of:
|
||||
|
||||
* Json serializer
|
||||
* Multipart upload
|
||||
* HTTP Basic/Digest authentication support
|
||||
* Pluggable object serialization
|
||||
* background processing support
|
||||
|
||||
100% Swift 2.0.
|
||||
|
||||
| | Project Info |
|
||||
| --------------- | ------------- |
|
||||
| License: | Apache License, Version 2.0 |
|
||||
| Build: | CocoaPods |
|
||||
| Documentation: | http://aerogear.org/ios/ |
|
||||
| Issue tracker: | https://issues.jboss.org/browse/AGIOS |
|
||||
| Mailing lists: | [aerogear-users](http://aerogear-users.1116366.n5.nabble.com/) ([subscribe](https://lists.jboss.org/mailman/listinfo/aerogear-users)) |
|
||||
| | [aerogear-dev](http://aerogear-dev.1069024.n5.nabble.com/) ([subscribe](https://lists.jboss.org/mailman/listinfo/aerogear-dev)) |
|
||||
|
||||
## Example Usage
|
||||
|
||||
To perform an HTTP request use the convenient methods found in the Http object. Here is an example usage:
|
||||
|
||||
```swift
|
||||
let http = Http(baseURL: "http://server.com")
|
||||
|
||||
http.request(.GET, path: "/get", completionHandler: {(response, error) in
|
||||
// handle response
|
||||
})
|
||||
|
||||
http.request(.POST, path: "/post", parameters: ["key": "value"],
|
||||
completionHandler: {(response, error) in
|
||||
// handle response
|
||||
})
|
||||
...
|
||||
```
|
||||
|
||||
### Authentication
|
||||
|
||||
The library also leverages the build-in foundation support for http/digest authentication and exposes a convenient interface by allowing the credential object to be passed on the request. Here is an example:
|
||||
|
||||
> **NOTE:** It is advised that HTTPS should be used when performing authentication of this type
|
||||
|
||||
```swift
|
||||
let credential = NSURLCredential(user: "john",
|
||||
password: "pass",
|
||||
persistence: .None)
|
||||
|
||||
http.request(.GET, path: "/protected/endpoint", credential: credential,
|
||||
completionHandler: {(response, error) in
|
||||
// handle response
|
||||
})
|
||||
```
|
||||
|
||||
You can also set a credential per protection space, so it's automatically picked up once http challenge is requested by the server, thus omitting the need to pass the credential on each request. In this case, you must initialize the ```Http``` object with a custom session configuration object, that has its credentials storage initialized with your credentials:
|
||||
|
||||
```swift
|
||||
// create a protection space
|
||||
var protectionSpace = NSURLProtectionSpace(host: "httpbin.org",
|
||||
port: 443,
|
||||
protocol: NSURLProtectionSpaceHTTPS,
|
||||
realm: "me@kennethreitz.com",
|
||||
authenticationMethod: NSURLAuthenticationMethodHTTPDigest)
|
||||
|
||||
// setup credential
|
||||
// notice that we use '.ForSession' type otherwise credential storage will discard and
|
||||
// won't save it when doing 'credentialStorage.setDefaultCredential' later on
|
||||
let credential = NSURLCredential(user: user,
|
||||
password: password,
|
||||
persistence: .ForSession)
|
||||
|
||||
// assign it to credential storage
|
||||
var credentialStorage = NSURLCredentialStorage.sharedCredentialStorage()
|
||||
credentialStorage.setDefaultCredential(credential, forProtectionSpace: protectionSpace);
|
||||
|
||||
// set up default configuration and assign credential storage
|
||||
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
|
||||
configuration.URLCredentialStorage = credentialStorage
|
||||
|
||||
// assign custom configuration to Http
|
||||
var http = Http(baseURL: "http://httpbin.org", sessionConfig: configuration)
|
||||
|
||||
http.request(.GET, path: "/protected/endpoint", completionHandler: {(response, error) in
|
||||
// handle response
|
||||
})
|
||||
```
|
||||
|
||||
### OAuth2 Protocol Support
|
||||
|
||||
To support the OAuth2 protocol, we have created a separate library [aerogear-ios-oauth2](https://github.com/aerogear/aerogear-ios-oauth2) that can be easily integrated, in order to provide out-of-the-box support for communicated with OAuth2 protected endpoints. Please have a look at the "Http and OAuth2Module" section on our [documentation page](http://aerogear.org/docs/guides/aerogear-ios-2.X/Authorization/) for more information.
|
||||
|
||||
Do you want to try it on your end? Follow next section steps.
|
||||
|
||||
### Build, test and play with aerogear-ios-http
|
||||
|
||||
1. Clone this project
|
||||
|
||||
2. Get the dependencies
|
||||
|
||||
The project uses [OHHTTPStubs](https://github.com/AliSoftware/OHHTTPStubs) framework for stubbing its http network requests and utilizes [cocoapods](http://cocoapods.org) 0.36 release for handling its dependencies. As a pre-requisite, install [cocoapods](http://blog.cocoapods.org/CocoaPods-0.36/) and then install the pod. On the root directory of the project run:
|
||||
```bash
|
||||
pod install
|
||||
```
|
||||
3. open AeroGearHttp.xcworkspace
|
||||
|
||||
## Adding the library to your project
|
||||
To add the library in your project, you can either use [CocoaPods](http://cocoapods.org) or manual install in your project. See the respective sections below for instructions:
|
||||
|
||||
### Using [CocoaPods](http://cocoapods.org)
|
||||
Support for Swift frameworks is supported from [CocoaPods-0.36 release](http://blog.cocoapods.org/CocoaPods-0.36/) upwards. In your ```Podfile``` add:
|
||||
|
||||
```
|
||||
pod 'AeroGearHttp'
|
||||
```
|
||||
|
||||
and then:
|
||||
|
||||
```bash
|
||||
pod install
|
||||
```
|
||||
|
||||
to install your dependencies
|
||||
|
||||
### Manual Installation
|
||||
Follow these steps to add the library in your Swift project:
|
||||
|
||||
1. Add AeroGearHttp as a [submodule](http://git-scm.com/docs/git-submodule) in your project. Open a terminal and navigate to your project directory. Then enter:
|
||||
```bash
|
||||
git submodule add https://github.com/aerogear/aerogear-ios-http.git
|
||||
```
|
||||
2. Open the `aerogear-ios-http` folder, and drag the `AeroGearHttp.xcodeproj` into the file navigator in Xcode.
|
||||
3. In Xcode select your application target and under the "Targets" heading section, ensure that the 'iOS Deployment Target' matches the application target of AeroGearHttp.framework (Currently set to 8.0).
|
||||
5. Select the "Build Phases" heading section, expand the "Target Dependencies" group and add `AeroGearHttp.framework`.
|
||||
7. Click on the `+` button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add `AeroGearHttp.framework`.
|
||||
|
||||
|
||||
If you run into any problems, please [file an issue](http://issues.jboss.org/browse/AEROGEAR) and/or ask our [user mailing list](https://lists.jboss.org/mailman/listinfo/aerogear-users). You can also join our [dev mailing list](https://lists.jboss.org/mailman/listinfo/aerogear-dev).
|
||||
|
||||
## Documentation
|
||||
|
||||
For more details about the current release, please consult [our documentation](http://aerogear.org/ios/).
|
||||
|
||||
## Development
|
||||
|
||||
If you would like to help develop AeroGear you can join our [developer's mailing list](https://lists.jboss.org/mailman/listinfo/aerogear-dev), join #aerogear on Freenode, or shout at us on Twitter @aerogears.
|
||||
|
||||
Also takes some time and skim the [contributor guide](http://aerogear.org/docs/guides/Contributing/)
|
||||
|
||||
## Questions?
|
||||
|
||||
Join our [user mailing list](https://lists.jboss.org/mailman/listinfo/aerogear-users) for any questions or help! We really hope you enjoy app development with AeroGear!
|
||||
|
||||
## Found a bug?
|
||||
|
||||
If you found a bug please create a ticket for us on [Jira](https://issues.jboss.org/browse/AGIOS) with some steps to reproduce it.
|
||||
239
Pods/AeroGearOAuth2/AeroGearOAuth2/AccountManager.swift
generated
Normal file
239
Pods/AeroGearOAuth2/AeroGearOAuth2/AccountManager.swift
generated
Normal file
@ -0,0 +1,239 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
A Config object that setups facebook specific configuration parameters.
|
||||
*/
|
||||
public class FacebookConfig: Config {
|
||||
/**
|
||||
Init a Facebook configuration.
|
||||
:param: clientId OAuth2 credentials an unique string that is generated in the OAuth2 provider Developers Console.
|
||||
:param: clientSecret OAuth2 credentials an unique string that is generated in the OAuth2 provider Developers Console.
|
||||
:param: scopes an array of scopes the app is asking access to.
|
||||
:param: accountId this unique id is used by AccountManager to identify the OAuth2 client.
|
||||
:paream: isOpenIDConnect to identify if fetching id information is required.
|
||||
*/
|
||||
public init(clientId: String, clientSecret: String, scopes: [String], accountId: String? = nil, isOpenIDConnect: Bool = false) {
|
||||
super.init(base: "",
|
||||
authzEndpoint: "https://www.facebook.com/dialog/oauth",
|
||||
redirectURL: "fb\(clientId)://authorize/",
|
||||
accessTokenEndpoint: "https://graph.facebook.com/oauth/access_token",
|
||||
clientId: clientId,
|
||||
refreshTokenEndpoint: "https://graph.facebook.com/oauth/access_token",
|
||||
clientSecret: clientSecret,
|
||||
revokeTokenEndpoint: "https://www.facebook.com/me/permissions",
|
||||
isOpenIDConnect: isOpenIDConnect,
|
||||
userInfoEndpoint: isOpenIDConnect ? "https://graph.facebook.com/v2.2/me" : nil,
|
||||
scopes: scopes,
|
||||
accountId: accountId)
|
||||
// Add openIdConnect scope
|
||||
if self.isOpenIDConnect {
|
||||
if self.scopes[0].rangeOfString("public_profile") == nil {
|
||||
self.scopes[0] = self.scopes[0] + ", public_profile"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
A Config object that setups Google specific configuration parameters.
|
||||
*/
|
||||
public class GoogleConfig: Config {
|
||||
/**
|
||||
Init a Google configuration.
|
||||
:param: clientId OAuth2 credentials an unique string that is generated in the OAuth2 provider Developers Console.
|
||||
:param: scopes an array of scopes the app is asking access to.
|
||||
:param: accountId this unique id is used by AccountManager to identify the OAuth2 client.
|
||||
:paream: isOpenIDConnect to identify if fetching id information is required.
|
||||
*/
|
||||
public init(clientId: String, scopes: [String], accountId: String? = nil, isOpenIDConnect: Bool = false) {
|
||||
let bundleString = NSBundle.mainBundle().bundleIdentifier ?? "google"
|
||||
super.init(base: "https://accounts.google.com",
|
||||
authzEndpoint: "o/oauth2/auth",
|
||||
redirectURL: "\(bundleString):/oauth2Callback",
|
||||
accessTokenEndpoint: "o/oauth2/token",
|
||||
clientId: clientId,
|
||||
refreshTokenEndpoint: "o/oauth2/token",
|
||||
revokeTokenEndpoint: "rest/revoke",
|
||||
isOpenIDConnect: isOpenIDConnect,
|
||||
userInfoEndpoint: isOpenIDConnect ? "https://www.googleapis.com/plus/v1/people/me/openIdConnect" : nil,
|
||||
scopes: scopes,
|
||||
accountId: accountId)
|
||||
// Add openIdConnect scope
|
||||
if self.isOpenIDConnect {
|
||||
self.scopes += ["openid", "email", "profile"]
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
A Config object that setups Keycloak specific configuration parameters.
|
||||
*/
|
||||
public class KeycloakConfig: Config {
|
||||
/**
|
||||
Init a Keycloak configuration.
|
||||
:param: clientId OAuth2 credentials an unique string that is generated in the OAuth2 provider Developers Console.
|
||||
:param: host to identify where is the keycloak server located.
|
||||
:param: realm to identify which realm to use. A realm grup a set of application/oauth2 client together.
|
||||
:paream: isOpenIDConnect to identify if fetching id information is required.
|
||||
*/
|
||||
public init(clientId: String, host: String, realm: String? = nil, isOpenIDConnect: Bool = false) {
|
||||
let bundleString = NSBundle.mainBundle().bundleIdentifier ?? "keycloak"
|
||||
let defaulRealmName = String(format: "%@-realm", clientId)
|
||||
let realm = realm ?? defaulRealmName
|
||||
super.init(base: String(format: "%@/auth", host),
|
||||
authzEndpoint: String(format: "realms/%@/tokens/login", realm),
|
||||
redirectURL: "\(bundleString)://oauth2Callback",
|
||||
accessTokenEndpoint: String(format: "realms/%@/tokens/access/codes", realm),
|
||||
clientId: clientId,
|
||||
refreshTokenEndpoint: String(format: "realms/%@/tokens/refresh", realm),
|
||||
revokeTokenEndpoint: String(format: "realms/%@/tokens/logout", realm),
|
||||
isOpenIDConnect: isOpenIDConnect)
|
||||
// Add openIdConnect scope
|
||||
if self.isOpenIDConnect {
|
||||
self.scopes += ["openid", "email", "profile"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
An account manager used to instantiate, store and retrieve OAuth2 modules.
|
||||
*/
|
||||
public class AccountManager {
|
||||
/// List of OAuth2 modules available for a given app. Each module is linked to an OAuht2Session which securely store the tokens.
|
||||
var modules: [String: OAuth2Module]
|
||||
|
||||
init() {
|
||||
self.modules = [String: OAuth2Module]()
|
||||
}
|
||||
|
||||
/// access a shared instance of an account manager
|
||||
public class var sharedInstance: AccountManager {
|
||||
struct Singleton {
|
||||
static let instance = AccountManager()
|
||||
}
|
||||
return Singleton.instance
|
||||
}
|
||||
|
||||
/**
|
||||
Instantiate an OAuth2 Module using the configuration object passed in and adds it to the account manager. It uses the OAuth2Session account_id as the name that this module will be stored in.
|
||||
|
||||
:param: config the configuration object to use to setup an OAuth2 module.
|
||||
:param: moduleClass the type of the OAuth2 module to instantiate.
|
||||
|
||||
:returns: the OAuth2 module
|
||||
*/
|
||||
public class func addAccount(config: Config, moduleClass: OAuth2Module.Type) -> OAuth2Module {
|
||||
var myModule:OAuth2Module
|
||||
myModule = moduleClass.init(config: config)
|
||||
// TODO check accountId is unique in modules list
|
||||
sharedInstance.modules[myModule.oauth2Session.accountId] = myModule
|
||||
return myModule
|
||||
}
|
||||
|
||||
/**
|
||||
Removes an OAuth2 module
|
||||
|
||||
:param: name the name that the OAuth2 module was bound to.
|
||||
:param: config the configuration object to use to setup an OAuth2 module.
|
||||
:param: moduleClass the type of the OAuth2 module to instantiate.
|
||||
|
||||
:returns: the OAuth2module or nil if not found
|
||||
*/
|
||||
public class func removeAccount(name: String, config: Config, moduleClass: OAuth2Module.Type) -> OAuth2Module? {
|
||||
return sharedInstance.modules.removeValueForKey(name)
|
||||
}
|
||||
|
||||
/**
|
||||
Retrieves an OAuth2 module by a name
|
||||
|
||||
:param: name the name that the OAuth2 module was bound to.
|
||||
|
||||
:returns: the OAuth2module or nil if not found.
|
||||
*/
|
||||
public class func getAccountByName(name: String) -> OAuth2Module? {
|
||||
return sharedInstance.modules[name]
|
||||
}
|
||||
|
||||
/**
|
||||
Retrieves a list of OAuth2 modules bound to specific clientId.
|
||||
|
||||
:param: clientId the client it that the oauth2 module was bound to.
|
||||
|
||||
:returns: the OAuth2module or nil if not found.
|
||||
*/
|
||||
public class func getAccountsByClienId(clientId: String) -> [OAuth2Module] {
|
||||
let modules: [OAuth2Module] = [OAuth2Module](sharedInstance.modules.values)
|
||||
return modules.filter {$0.config.clientId == clientId }
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
Retrieves an OAuth2 module by using a configuration object.
|
||||
|
||||
:param: config the Config object that this oauth2 module was used to instantiate.
|
||||
|
||||
:returns: the OAuth2module or nil if not found.
|
||||
*/
|
||||
public class func getAccountByConfig(config: Config) -> OAuth2Module? {
|
||||
if config.accountId != nil {
|
||||
return sharedInstance.modules[config.accountId!]
|
||||
} else {
|
||||
let modules = getAccountsByClienId(config.clientId)
|
||||
if modules.count > 0 {
|
||||
return modules[0]
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Convenient method to retrieve a Facebook oauth2 module.
|
||||
|
||||
:param: config a Facebook configuration object. See FacebookConfig.
|
||||
|
||||
:returns: a Facebook OAuth2 module.
|
||||
*/
|
||||
public class func addFacebookAccount(config: FacebookConfig) -> FacebookOAuth2Module {
|
||||
return addAccount(config, moduleClass: FacebookOAuth2Module.self) as! FacebookOAuth2Module
|
||||
}
|
||||
|
||||
/**
|
||||
Convenient method to retrieve a Google oauth2 module ready to be used.
|
||||
|
||||
:param: config a google configuration object. See GoogleConfig.
|
||||
|
||||
:returns: a google OAuth2 module.
|
||||
*/
|
||||
public class func addGoogleAccount(config: GoogleConfig) -> OAuth2Module {
|
||||
return addAccount(config, moduleClass: OAuth2Module.self)
|
||||
}
|
||||
|
||||
/**
|
||||
Convenient method to retrieve a Keycloak oauth2 module ready to be used.
|
||||
|
||||
:param: config a Keycloak configuration object. See KeycloakConfig.
|
||||
|
||||
:returns: a Keycloak OAuth2 module.
|
||||
*/
|
||||
public class func addKeycloakAccount(config: KeycloakConfig) -> KeycloakOAuth2Module {
|
||||
return addAccount(config, moduleClass: KeycloakOAuth2Module.self) as! KeycloakOAuth2Module
|
||||
}
|
||||
|
||||
}
|
||||
121
Pods/AeroGearOAuth2/AeroGearOAuth2/Config.swift
generated
Normal file
121
Pods/AeroGearOAuth2/AeroGearOAuth2/Config.swift
generated
Normal file
@ -0,0 +1,121 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Configuration object to setup an OAuth2 module
|
||||
*/
|
||||
public class Config {
|
||||
/**
|
||||
Applies the baseURL to the configuration.
|
||||
*/
|
||||
public let baseURL: String
|
||||
|
||||
/**
|
||||
Applies the "callback URL" once request token issued.
|
||||
*/
|
||||
public let redirectURL: String
|
||||
|
||||
/**
|
||||
Applies the "authorization endpoint" to the request token.
|
||||
*/
|
||||
public var authzEndpoint: String
|
||||
|
||||
/**
|
||||
Applies the "access token endpoint" to the exchange code for access token.
|
||||
*/
|
||||
public var accessTokenEndpoint: String
|
||||
|
||||
/**
|
||||
Endpoint for request to invalidate both accessToken and refreshToken.
|
||||
*/
|
||||
public let revokeTokenEndpoint: String?
|
||||
|
||||
/**
|
||||
Endpoint for request a refreshToken.
|
||||
*/
|
||||
public let refreshTokenEndpoint: String?
|
||||
|
||||
/**
|
||||
Endpoint for OpenID Connect to get user information.
|
||||
*/
|
||||
public let userInfoEndpoint: String?
|
||||
|
||||
/**
|
||||
Boolean to indicate whether OpenID Connect on authorization code grant flow is used.
|
||||
*/
|
||||
public var isOpenIDConnect: Bool
|
||||
|
||||
/**
|
||||
Applies the various scopes of the authorization.
|
||||
*/
|
||||
public var scopes: [String]
|
||||
|
||||
var scope: String {
|
||||
get {
|
||||
// Create a string to concatenate all scopes existing in the _scopes array.
|
||||
var scopeString = ""
|
||||
for scope in self.scopes {
|
||||
scopeString += scope.urlEncode()
|
||||
// If the current scope is other than the last one, then add the "+" sign to the string to separate the scopes.
|
||||
if (scope != self.scopes.last) {
|
||||
scopeString += "+"
|
||||
}
|
||||
}
|
||||
return scopeString
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Applies the "client id" obtained with the client registration process.
|
||||
*/
|
||||
public let clientId: String
|
||||
|
||||
/**
|
||||
Applies the "client secret" obtained with the client registration process.
|
||||
*/
|
||||
public let clientSecret: String?
|
||||
|
||||
/**
|
||||
Account id is used with AccountManager to store tokens. AccountId is defined by the end-user
|
||||
and can be any String. If AccountManager is not used, this field is optional.
|
||||
*/
|
||||
public var accountId: String?
|
||||
|
||||
/**
|
||||
Boolean to indicate to either used a webview (if true) or an external browser (by default, false)
|
||||
for authorization code grant flow.
|
||||
*/
|
||||
public var isWebView: Bool = false
|
||||
|
||||
public init(base: String, authzEndpoint: String, redirectURL: String, accessTokenEndpoint: String, clientId: String, refreshTokenEndpoint: String? = nil, revokeTokenEndpoint: String? = nil, isOpenIDConnect:Bool = false, userInfoEndpoint: String? = nil, scopes: [String] = [], clientSecret: String? = nil, accountId: String? = nil, isWebView: Bool = false) {
|
||||
self.baseURL = base
|
||||
self.authzEndpoint = authzEndpoint
|
||||
self.redirectURL = redirectURL
|
||||
self.accessTokenEndpoint = accessTokenEndpoint
|
||||
self.refreshTokenEndpoint = refreshTokenEndpoint
|
||||
self.revokeTokenEndpoint = revokeTokenEndpoint
|
||||
self.isOpenIDConnect = isOpenIDConnect ?? false
|
||||
self.userInfoEndpoint = userInfoEndpoint
|
||||
self.scopes = scopes
|
||||
self.clientId = clientId
|
||||
self.clientSecret = clientSecret
|
||||
self.accountId = accountId
|
||||
self.isWebView = isWebView
|
||||
}
|
||||
}
|
||||
55
Pods/AeroGearOAuth2/AeroGearOAuth2/DateUtils.swift
generated
Normal file
55
Pods/AeroGearOAuth2/AeroGearOAuth2/DateUtils.swift
generated
Normal file
@ -0,0 +1,55 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Handy extensions to NSDate
|
||||
*/
|
||||
extension NSDate
|
||||
{
|
||||
|
||||
/**
|
||||
Initialize a date object using the given string.
|
||||
|
||||
:param: dateString the string that will be used to instantiate the date object. The string is expected to be in the format 'yyyy-MM-dd hh:mm:ss a'.
|
||||
|
||||
:returns: the NSDate object.
|
||||
*/
|
||||
public convenience init(dateString:String) {
|
||||
let dateStringFormatter = NSDateFormatter()
|
||||
dateStringFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss a"
|
||||
let d = dateStringFormatter.dateFromString(dateString)
|
||||
if let unwrappedDate = d {
|
||||
self.init(timeInterval:0, sinceDate:unwrappedDate)
|
||||
} else {
|
||||
self.init()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
Returns a string of the date object using the format 'yyyy-MM-dd hh:mm:ss a'.
|
||||
|
||||
:returns: a formatted string object.
|
||||
*/
|
||||
public func toString() -> String {
|
||||
let dateStringFormatter = NSDateFormatter()
|
||||
dateStringFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss a"
|
||||
return dateStringFormatter.stringFromDate(self)
|
||||
}
|
||||
}
|
||||
135
Pods/AeroGearOAuth2/AeroGearOAuth2/FacebookOAuth2Module.swift
generated
Normal file
135
Pods/AeroGearOAuth2/AeroGearOAuth2/FacebookOAuth2Module.swift
generated
Normal file
@ -0,0 +1,135 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
import AeroGearHttp
|
||||
|
||||
/**
|
||||
An OAuth2Module subclass specific to 'Facebook' authorization
|
||||
*/
|
||||
public class FacebookOAuth2Module: OAuth2Module {
|
||||
|
||||
public required init(config: Config, session: OAuth2Session?, requestSerializer: RequestSerializer, responseSerializer: ResponseSerializer) {
|
||||
super.init(config: config, session: session, requestSerializer: JsonRequestSerializer(), responseSerializer: StringResponseSerializer())
|
||||
}
|
||||
|
||||
/**
|
||||
Exchange an authorization code for an access token.
|
||||
|
||||
:param: code the 'authorization' code to exchange for an access token.
|
||||
:param: completionHandler A block object to be executed when the request operation finishes.
|
||||
*/
|
||||
override public func exchangeAuthorizationCodeForAccessToken(code: String, completionHandler: (AnyObject?, NSError?) -> Void) {
|
||||
var paramDict: [String: String] = ["code": code, "client_id": config.clientId, "redirect_uri": config.redirectURL, "grant_type":"authorization_code"]
|
||||
|
||||
if let unwrapped = config.clientSecret {
|
||||
paramDict["client_secret"] = unwrapped
|
||||
}
|
||||
|
||||
http.request(.POST, path: config.accessTokenEndpoint, parameters: paramDict, completionHandler: { (response, error) in
|
||||
|
||||
if (error != nil) {
|
||||
completionHandler(nil, error)
|
||||
return
|
||||
}
|
||||
|
||||
if let unwrappedResponse = response as? String {
|
||||
var accessToken: String? = nil
|
||||
var expiredIn: String? = nil
|
||||
|
||||
let charSet: NSMutableCharacterSet = NSMutableCharacterSet()
|
||||
charSet.addCharactersInString("&=")
|
||||
let array = unwrappedResponse.componentsSeparatedByCharactersInSet(charSet)
|
||||
for (index, elt) in array.enumerate() {
|
||||
if elt == "access_token" {
|
||||
accessToken = array[index+1]
|
||||
}
|
||||
}
|
||||
for (index, elt) in array.enumerate() {
|
||||
if elt == "expires" {
|
||||
expiredIn = array[index+1]
|
||||
}
|
||||
}
|
||||
self.oauth2Session.saveAccessToken(accessToken, refreshToken: nil, accessTokenExpiration: expiredIn, refreshTokenExpiration: nil)
|
||||
completionHandler(accessToken, nil)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
Request to revoke access.
|
||||
|
||||
:param: completionHandler A block object to be executed when the request operation finishes.
|
||||
*/
|
||||
override public func revokeAccess(completionHandler: (AnyObject?, NSError?) -> Void) {
|
||||
// return if not yet initialized
|
||||
if (self.oauth2Session.accessToken == nil) {
|
||||
return;
|
||||
}
|
||||
let paramDict:[String:String] = ["access_token":self.oauth2Session.accessToken!]
|
||||
|
||||
http.request(.DELETE, path: config.revokeTokenEndpoint!, parameters: paramDict, completionHandler: { (response, error) in
|
||||
|
||||
if (error != nil) {
|
||||
completionHandler(nil, error)
|
||||
return
|
||||
}
|
||||
|
||||
self.oauth2Session.clearTokens()
|
||||
completionHandler(response!, nil)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
Gateway to request authorization access
|
||||
|
||||
:param: completionHandler A block object to be executed when the request operation finishes.
|
||||
*/
|
||||
override public func login(completionHandler: (AnyObject?, OpenIDClaim?, NSError?) -> Void) {
|
||||
self.requestAccess { (response:AnyObject?, error:NSError?) -> Void in
|
||||
if (error != nil) {
|
||||
completionHandler(nil, nil, error)
|
||||
return
|
||||
}
|
||||
var paramDict: [String: String] = [:]
|
||||
if response != nil {
|
||||
paramDict = ["access_token": response! as! String]
|
||||
}
|
||||
if let userInfoEndpoint = self.config.userInfoEndpoint {
|
||||
|
||||
self.http.request(.GET, path: userInfoEndpoint, parameters: paramDict, completionHandler: {(responseObject, error) in
|
||||
if (error != nil) {
|
||||
completionHandler(nil, nil, error)
|
||||
return
|
||||
}
|
||||
if let unwrappedResponse = responseObject as? String {
|
||||
let data = unwrappedResponse.dataUsingEncoding(NSUTF8StringEncoding)
|
||||
let json: AnyObject? = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0))
|
||||
var openIDClaims: FacebookOpenIDClaim?
|
||||
if let unwrappedResponse = json as? [String: AnyObject] {
|
||||
openIDClaims = FacebookOpenIDClaim(fromDict: unwrappedResponse)
|
||||
}
|
||||
completionHandler(response, openIDClaims, nil)
|
||||
}
|
||||
})
|
||||
} else {
|
||||
completionHandler(nil, nil, NSError(domain: "OAuth2Module", code: 0, userInfo: ["OpenID Connect" : "No UserInfo endpoint available in config"]))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
126
Pods/AeroGearOAuth2/AeroGearOAuth2/KeycloakOAuth2Module.swift
generated
Normal file
126
Pods/AeroGearOAuth2/AeroGearOAuth2/KeycloakOAuth2Module.swift
generated
Normal file
@ -0,0 +1,126 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
An OAuth2Module subclass specific to 'Keycloak' authorization
|
||||
*/
|
||||
public class KeycloakOAuth2Module: OAuth2Module {
|
||||
|
||||
public override func revokeAccess(completionHandler: (AnyObject?, NSError?) -> Void) {
|
||||
// return if not yet initialized
|
||||
if (self.oauth2Session.accessToken == nil) {
|
||||
return;
|
||||
}
|
||||
let paramDict:[String:String] = [ "client_id": config.clientId, "refresh_token": self.oauth2Session.refreshToken!]
|
||||
http.request(.POST, path: config.revokeTokenEndpoint!, parameters: paramDict, completionHandler: { (response, error) in
|
||||
if (error != nil) {
|
||||
completionHandler(nil, error)
|
||||
return
|
||||
}
|
||||
|
||||
self.oauth2Session.clearTokens()
|
||||
completionHandler(response, nil)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
Gateway to login with OpenIDConnect
|
||||
|
||||
:param: completionHandler A block object to be executed when the request operation finishes.
|
||||
*/
|
||||
public override func login(completionHandler: (AnyObject?, OpenIDClaim?, NSError?) -> Void) {
|
||||
var openIDClaims: OpenIDClaim?
|
||||
|
||||
self.requestAccess { (response: AnyObject?, error: NSError?) -> Void in
|
||||
if (error != nil) {
|
||||
completionHandler(nil, nil, error)
|
||||
return
|
||||
}
|
||||
let accessToken = response as? String
|
||||
if let accessToken = accessToken {
|
||||
let token = self.decode(accessToken)
|
||||
if let decodedToken = token {
|
||||
openIDClaims = OpenIDClaim(fromDict: decodedToken)
|
||||
}
|
||||
}
|
||||
completionHandler(accessToken, openIDClaims, nil)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Request to refresh an access token.
|
||||
|
||||
:param: completionHandler A block object to be executed when the request operation finishes.
|
||||
*/
|
||||
public override func refreshAccessToken(completionHandler: (AnyObject?, NSError?) -> Void) {
|
||||
if let unwrappedRefreshToken = self.oauth2Session.refreshToken {
|
||||
var paramDict: [String: String] = ["refresh_token": unwrappedRefreshToken, "client_id": config.clientId, "grant_type": "refresh_token"]
|
||||
if (config.clientSecret != nil) {
|
||||
paramDict["client_secret"] = config.clientSecret!
|
||||
}
|
||||
|
||||
http.request(.POST, path: config.refreshTokenEndpoint!, parameters: paramDict, completionHandler: { (response, error) in
|
||||
if (error != nil) {
|
||||
completionHandler(nil, error)
|
||||
return
|
||||
}
|
||||
|
||||
if let unwrappedResponse = response as? [String: AnyObject] {
|
||||
let accessToken: String = unwrappedResponse["access_token"] as! String
|
||||
let refreshToken: String = unwrappedResponse["refresh_token"] as! String
|
||||
let expiration = unwrappedResponse["expires_in"] as! NSNumber
|
||||
let exp: String = expiration.stringValue
|
||||
let expirationRefresh = unwrappedResponse["refresh_expires_in"] as? NSNumber
|
||||
let expRefresh = expirationRefresh?.stringValue
|
||||
|
||||
// in Keycloak refresh token get refreshed every time you use them
|
||||
self.oauth2Session.saveAccessToken(accessToken, refreshToken: refreshToken, accessTokenExpiration: exp, refreshTokenExpiration: expRefresh)
|
||||
completionHandler(accessToken, nil);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func decode(token: String) -> [String: AnyObject]? {
|
||||
let string = token.componentsSeparatedByString(".")
|
||||
let toDecode = string[1] as String
|
||||
|
||||
|
||||
var stringtoDecode: String = toDecode.stringByReplacingOccurrencesOfString("-", withString: "+") // 62nd char of encoding
|
||||
stringtoDecode = stringtoDecode.stringByReplacingOccurrencesOfString("_", withString: "/") // 63rd char of encoding
|
||||
switch (stringtoDecode.utf16.count % 4) {
|
||||
case 2: stringtoDecode = "\(stringtoDecode)=="
|
||||
case 3: stringtoDecode = "\(stringtoDecode)="
|
||||
default: // nothing to do stringtoDecode can stay the same
|
||||
print("")
|
||||
}
|
||||
let dataToDecode = NSData(base64EncodedString: stringtoDecode, options: [])
|
||||
let base64DecodedString = NSString(data: dataToDecode!, encoding: NSUTF8StringEncoding)
|
||||
|
||||
var values: [String: AnyObject]?
|
||||
if let string = base64DecodedString {
|
||||
if let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) {
|
||||
values = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? [String : AnyObject]
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
}
|
||||
364
Pods/AeroGearOAuth2/AeroGearOAuth2/OAuth2Module.swift
generated
Normal file
364
Pods/AeroGearOAuth2/AeroGearOAuth2/OAuth2Module.swift
generated
Normal file
@ -0,0 +1,364 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
import UIKit
|
||||
import AeroGearHttp
|
||||
|
||||
/**
|
||||
Notification constants emitted during oauth authorization flow.
|
||||
*/
|
||||
public let AGAppLaunchedWithURLNotification = "AGAppLaunchedWithURLNotification"
|
||||
public let AGAppDidBecomeActiveNotification = "AGAppDidBecomeActiveNotification"
|
||||
public let AGAuthzErrorDomain = "AGAuthzErrorDomain"
|
||||
|
||||
/**
|
||||
The current state that this module is in.
|
||||
|
||||
- AuthorizationStatePendingExternalApproval: the module is waiting external approval.
|
||||
- AuthorizationStateApproved: the oauth flow has been approved.
|
||||
- AuthorizationStateUnknown: the oauth flow is in unknown state (e.g. user clicked cancel).
|
||||
*/
|
||||
enum AuthorizationState {
|
||||
case AuthorizationStatePendingExternalApproval
|
||||
case AuthorizationStateApproved
|
||||
case AuthorizationStateUnknown
|
||||
}
|
||||
|
||||
/**
|
||||
Parent class of any OAuth2 module implementing generic OAuth2 authorization flow.
|
||||
*/
|
||||
public class OAuth2Module: AuthzModule {
|
||||
let config: Config
|
||||
var http: Http
|
||||
|
||||
var oauth2Session: OAuth2Session
|
||||
var applicationLaunchNotificationObserver: NSObjectProtocol?
|
||||
var applicationDidBecomeActiveNotificationObserver: NSObjectProtocol?
|
||||
var state: AuthorizationState
|
||||
var webView: OAuth2WebViewController?
|
||||
/**
|
||||
Initialize an OAuth2 module.
|
||||
|
||||
:param: config the configuration object that setups the module.
|
||||
:param: session the session that that module will be bound to.
|
||||
:param: requestSerializer the actual request serializer to use when performing requests.
|
||||
:param: responseSerializer the actual response serializer to use upon receiving a response.
|
||||
|
||||
:returns: the newly initialized OAuth2Module.
|
||||
*/
|
||||
public required init(config: Config, session: OAuth2Session? = nil, requestSerializer: RequestSerializer = HttpRequestSerializer(), responseSerializer: ResponseSerializer = JsonResponseSerializer()) {
|
||||
if (config.accountId == nil) {
|
||||
config.accountId = "ACCOUNT_FOR_CLIENTID_\(config.clientId)"
|
||||
}
|
||||
if (session == nil) {
|
||||
self.oauth2Session = TrustedPersistantOAuth2Session(accountId: config.accountId!)
|
||||
} else {
|
||||
self.oauth2Session = session!
|
||||
}
|
||||
|
||||
self.config = config
|
||||
if config.isWebView {
|
||||
self.webView = OAuth2WebViewController()
|
||||
}
|
||||
self.http = Http(baseURL: config.baseURL, requestSerializer: requestSerializer, responseSerializer: responseSerializer)
|
||||
self.state = .AuthorizationStateUnknown
|
||||
}
|
||||
|
||||
// MARK: Public API - To be overriden if necessary by OAuth2 specific adapter
|
||||
|
||||
/**
|
||||
Request an authorization code.
|
||||
|
||||
:param: completionHandler A block object to be executed when the request operation finishes.
|
||||
*/
|
||||
public func requestAuthorizationCode(completionHandler: (AnyObject?, NSError?) -> Void) {
|
||||
// register with the notification system in order to be notified when the 'authorization' process completes in the
|
||||
// external browser, and the oauth code is available so that we can then proceed to request the 'access_token'
|
||||
// from the server.
|
||||
applicationLaunchNotificationObserver = NSNotificationCenter.defaultCenter().addObserverForName(AGAppLaunchedWithURLNotification, object: nil, queue: nil, usingBlock: { (notification: NSNotification!) -> Void in
|
||||
self.extractCode(notification, completionHandler: completionHandler)
|
||||
if ( self.webView != nil ) {
|
||||
UIApplication.sharedApplication().keyWindow?.rootViewController?.dismissViewControllerAnimated(true, completion: nil)
|
||||
}
|
||||
})
|
||||
|
||||
// register to receive notification when the application becomes active so we
|
||||
// can clear any pending authorization requests which are not completed properly,
|
||||
// that is a user switched into the app without Accepting or Cancelling the authorization
|
||||
// request in the external browser process.
|
||||
applicationDidBecomeActiveNotificationObserver = NSNotificationCenter.defaultCenter().addObserverForName(AGAppDidBecomeActiveNotification, object:nil, queue:nil, usingBlock: { (note: NSNotification!) -> Void in
|
||||
// check the state
|
||||
if (self.state == .AuthorizationStatePendingExternalApproval) {
|
||||
// unregister
|
||||
self.stopObserving()
|
||||
// ..and update state
|
||||
self.state = .AuthorizationStateUnknown;
|
||||
}
|
||||
})
|
||||
|
||||
// update state to 'Pending'
|
||||
self.state = .AuthorizationStatePendingExternalApproval
|
||||
|
||||
// calculate final url
|
||||
let params = "?scope=\(config.scope)&redirect_uri=\(config.redirectURL.urlEncode())&client_id=\(config.clientId)&response_type=code"
|
||||
guard let computedUrl = http.calculateURL(config.baseURL, url:config.authzEndpoint) else {
|
||||
let error = NSError(domain:AGAuthzErrorDomain, code:0, userInfo:["NSLocalizedDescriptionKey": "Malformatted URL."])
|
||||
completionHandler(nil, error)
|
||||
return
|
||||
}
|
||||
let url = NSURL(string:computedUrl.absoluteString + params)
|
||||
if let url = url {
|
||||
if self.webView != nil {
|
||||
self.webView!.targetURL = url
|
||||
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(self.webView!, animated: true, completion: nil)
|
||||
} else {
|
||||
UIApplication.sharedApplication().openURL(url)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Request to refresh an access token.
|
||||
|
||||
:param: completionHandler A block object to be executed when the request operation finishes.
|
||||
*/
|
||||
public func refreshAccessToken(completionHandler: (AnyObject?, NSError?) -> Void) {
|
||||
if let unwrappedRefreshToken = self.oauth2Session.refreshToken {
|
||||
var paramDict: [String: String] = ["refresh_token": unwrappedRefreshToken, "client_id": config.clientId, "grant_type": "refresh_token"]
|
||||
if (config.clientSecret != nil) {
|
||||
paramDict["client_secret"] = config.clientSecret!
|
||||
}
|
||||
|
||||
http.request(.POST, path: config.refreshTokenEndpoint!, parameters: paramDict, completionHandler: { (response, error) in
|
||||
if (error != nil) {
|
||||
completionHandler(nil, error)
|
||||
return
|
||||
}
|
||||
|
||||
if let unwrappedResponse = response as? [String: AnyObject] {
|
||||
let accessToken: String = unwrappedResponse["access_token"] as! String
|
||||
let expiration = unwrappedResponse["expires_in"] as! NSNumber
|
||||
let exp: String = expiration.stringValue
|
||||
|
||||
self.oauth2Session.saveAccessToken(accessToken, refreshToken: unwrappedRefreshToken, accessTokenExpiration: exp, refreshTokenExpiration: nil)
|
||||
|
||||
completionHandler(unwrappedResponse["access_token"], nil);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Exchange an authorization code for an access token.
|
||||
|
||||
:param: code the 'authorization' code to exchange for an access token.
|
||||
:param: completionHandler A block object to be executed when the request operation finishes.
|
||||
*/
|
||||
public func exchangeAuthorizationCodeForAccessToken(code: String, completionHandler: (AnyObject?, NSError?) -> Void) {
|
||||
var paramDict: [String: String] = ["code": code, "client_id": config.clientId, "redirect_uri": config.redirectURL, "grant_type":"authorization_code"]
|
||||
|
||||
if let unwrapped = config.clientSecret {
|
||||
paramDict["client_secret"] = unwrapped
|
||||
}
|
||||
|
||||
http.request(.POST, path: config.accessTokenEndpoint, parameters: paramDict, completionHandler: {(responseObject, error) in
|
||||
if (error != nil) {
|
||||
completionHandler(nil, error)
|
||||
return
|
||||
}
|
||||
|
||||
if let unwrappedResponse = responseObject as? [String: AnyObject] {
|
||||
let accessToken: String = unwrappedResponse["access_token"] as! String
|
||||
let refreshToken: String? = unwrappedResponse["refresh_token"] as? String
|
||||
let expiration = unwrappedResponse["expires_in"] as? NSNumber
|
||||
let exp: String? = expiration?.stringValue
|
||||
// expiration for refresh token is used in Keycloak
|
||||
let expirationRefresh = unwrappedResponse["refresh_expires_in"] as? NSNumber
|
||||
let expRefresh = expirationRefresh?.stringValue
|
||||
|
||||
self.oauth2Session.saveAccessToken(accessToken, refreshToken: refreshToken, accessTokenExpiration: exp, refreshTokenExpiration: expRefresh)
|
||||
completionHandler(accessToken, nil)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
Gateway to request authorization access.
|
||||
|
||||
:param: completionHandler A block object to be executed when the request operation finishes.
|
||||
*/
|
||||
public func requestAccess(completionHandler: (AnyObject?, NSError?) -> Void) {
|
||||
if (self.oauth2Session.accessToken != nil && self.oauth2Session.tokenIsNotExpired()) {
|
||||
// we already have a valid access token, nothing more to be done
|
||||
completionHandler(self.oauth2Session.accessToken!, nil);
|
||||
} else if (self.oauth2Session.refreshToken != nil && self.oauth2Session.refreshTokenIsNotExpired()) {
|
||||
// need to refresh token
|
||||
self.refreshAccessToken(completionHandler)
|
||||
} else {
|
||||
// ask for authorization code and once obtained exchange code for access token
|
||||
self.requestAuthorizationCode(completionHandler)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Gateway to provide authentication using the Authorization Code Flow with OpenID Connect.
|
||||
|
||||
:param: completionHandler A block object to be executed when the request operation finishes.
|
||||
*/
|
||||
public func login(completionHandler: (AnyObject?, OpenIDClaim?, NSError?) -> Void) {
|
||||
|
||||
self.requestAccess { (response:AnyObject?, error:NSError?) -> Void in
|
||||
|
||||
if (error != nil) {
|
||||
completionHandler(nil, nil, error)
|
||||
return
|
||||
}
|
||||
var paramDict: [String: String] = [:]
|
||||
if response != nil {
|
||||
paramDict = ["access_token": response! as! String]
|
||||
}
|
||||
if let userInfoEndpoint = self.config.userInfoEndpoint {
|
||||
|
||||
self.http.request(.GET, path:userInfoEndpoint, parameters: paramDict, completionHandler: {(responseObject, error) in
|
||||
if (error != nil) {
|
||||
completionHandler(nil, nil, error)
|
||||
return
|
||||
}
|
||||
var openIDClaims: OpenIDClaim?
|
||||
if let unwrappedResponse = responseObject as? [String: AnyObject] {
|
||||
openIDClaims = OpenIDClaim(fromDict: unwrappedResponse)
|
||||
}
|
||||
completionHandler(response, openIDClaims, nil)
|
||||
})
|
||||
} else {
|
||||
completionHandler(nil, nil, NSError(domain: "OAuth2Module", code: 0, userInfo: ["OpenID Connect" : "No UserInfo endpoint available in config"]))
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
Request to revoke access.
|
||||
|
||||
:param: completionHandler A block object to be executed when the request operation finishes.
|
||||
*/
|
||||
public func revokeAccess(completionHandler: (AnyObject?, NSError?) -> Void) {
|
||||
// return if not yet initialized
|
||||
if (self.oauth2Session.accessToken == nil) {
|
||||
return;
|
||||
}
|
||||
let paramDict:[String:String] = ["token":self.oauth2Session.accessToken!]
|
||||
|
||||
http.request(.POST, path: config.revokeTokenEndpoint!, parameters: paramDict, completionHandler: { (response, error) in
|
||||
if (error != nil) {
|
||||
completionHandler(nil, error)
|
||||
return
|
||||
}
|
||||
|
||||
self.oauth2Session.clearTokens()
|
||||
completionHandler(response, nil)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
Return any authorization fields.
|
||||
|
||||
:returns: a dictionary filled with the authorization fields.
|
||||
*/
|
||||
public func authorizationFields() -> [String: String]? {
|
||||
if (self.oauth2Session.accessToken == nil) {
|
||||
return nil
|
||||
} else {
|
||||
return ["Authorization":"Bearer \(self.oauth2Session.accessToken!)"]
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Returns a boolean indicating whether authorization has been granted.
|
||||
|
||||
:returns: true if authorized, false otherwise.
|
||||
*/
|
||||
public func isAuthorized() -> Bool {
|
||||
return self.oauth2Session.accessToken != nil && self.oauth2Session.tokenIsNotExpired()
|
||||
}
|
||||
|
||||
// MARK: Internal Methods
|
||||
|
||||
func extractCode(notification: NSNotification, completionHandler: (AnyObject?, NSError?) -> Void) {
|
||||
let url: NSURL? = (notification.userInfo as! [String: AnyObject])[UIApplicationLaunchOptionsURLKey] as? NSURL
|
||||
|
||||
// extract the code from the URL
|
||||
let code = self.parametersFromQueryString(url?.query)["code"]
|
||||
// if exists perform the exchange
|
||||
if (code != nil) {
|
||||
self.exchangeAuthorizationCodeForAccessToken(code!, completionHandler: completionHandler)
|
||||
// update state
|
||||
state = .AuthorizationStateApproved
|
||||
} else {
|
||||
|
||||
let error = NSError(domain:AGAuthzErrorDomain, code:0, userInfo:["NSLocalizedDescriptionKey": "User cancelled authorization."])
|
||||
completionHandler(nil, error)
|
||||
}
|
||||
// finally, unregister
|
||||
self.stopObserving()
|
||||
}
|
||||
|
||||
func parametersFromQueryString(queryString: String?) -> [String: String] {
|
||||
var parameters = [String: String]()
|
||||
if (queryString != nil) {
|
||||
let parameterScanner: NSScanner = NSScanner(string: queryString!)
|
||||
var name:NSString? = nil
|
||||
var value:NSString? = nil
|
||||
|
||||
while (parameterScanner.atEnd != true) {
|
||||
name = nil;
|
||||
parameterScanner.scanUpToString("=", intoString: &name)
|
||||
parameterScanner.scanString("=", intoString:nil)
|
||||
|
||||
value = nil
|
||||
parameterScanner.scanUpToString("&", intoString:&value)
|
||||
parameterScanner.scanString("&", intoString:nil)
|
||||
|
||||
if (name != nil && value != nil) {
|
||||
parameters[name!.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!] = value!.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return parameters;
|
||||
}
|
||||
|
||||
deinit {
|
||||
self.stopObserving()
|
||||
}
|
||||
|
||||
func stopObserving() {
|
||||
// clear all observers
|
||||
if (applicationLaunchNotificationObserver != nil) {
|
||||
NSNotificationCenter.defaultCenter().removeObserver(applicationLaunchNotificationObserver!)
|
||||
self.applicationLaunchNotificationObserver = nil;
|
||||
}
|
||||
|
||||
if (applicationDidBecomeActiveNotificationObserver != nil) {
|
||||
NSNotificationCenter.defaultCenter().removeObserver(applicationDidBecomeActiveNotificationObserver!)
|
||||
applicationDidBecomeActiveNotificationObserver = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
75
Pods/AeroGearOAuth2/AeroGearOAuth2/OAuth2Session.swift
generated
Normal file
75
Pods/AeroGearOAuth2/AeroGearOAuth2/OAuth2Session.swift
generated
Normal file
@ -0,0 +1,75 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
The protocol that an OAuth2 Session modules must adhere to and represent storage of oauth specific metadata. See TrustedPersistantOAuth2Session and UntrustedMemoryOAuth2Session as example implementations
|
||||
*/
|
||||
public protocol OAuth2Session {
|
||||
|
||||
/**
|
||||
The account id.
|
||||
*/
|
||||
var accountId: String {get}
|
||||
|
||||
/**
|
||||
The access token which expires.
|
||||
*/
|
||||
var accessToken: String? {get set}
|
||||
|
||||
/**
|
||||
The access token's expiration date.
|
||||
*/
|
||||
var accessTokenExpirationDate: NSDate? {get set}
|
||||
|
||||
/**
|
||||
The refresh token's expiration date.
|
||||
*/
|
||||
var refreshTokenExpirationDate: NSDate? {get set}
|
||||
|
||||
/**
|
||||
The refresh tokens. This toke does not expire and should be used to renew access token when expired.
|
||||
*/
|
||||
var refreshToken: String? {get set}
|
||||
|
||||
/**
|
||||
Check validity of accessToken. return true if still valid, false when expired.
|
||||
*/
|
||||
func tokenIsNotExpired() -> Bool
|
||||
|
||||
|
||||
/**
|
||||
Check validity of refreshToken. return true if still valid, false when expired.
|
||||
*/
|
||||
func refreshTokenIsNotExpired() -> Bool
|
||||
|
||||
/**
|
||||
Clears any tokens storage
|
||||
*/
|
||||
func clearTokens()
|
||||
|
||||
/**
|
||||
Save tokens information. Saving tokens allow you to refresh accesstoken transparently for the user without prompting
|
||||
for grant access.
|
||||
|
||||
:param: accessToken the access token.
|
||||
:param: refreshToken the refresh token.
|
||||
:param: accessTokenExpiration the expiration for the access token.
|
||||
:param: refreshTokenExpiration the expiration for the refresh token.
|
||||
*/
|
||||
func saveAccessToken(accessToken: String?, refreshToken: String?, accessTokenExpiration: String?, refreshTokenExpiration: String?)
|
||||
}
|
||||
53
Pods/AeroGearOAuth2/AeroGearOAuth2/OAuth2WebViewController.swift
generated
Normal file
53
Pods/AeroGearOAuth2/AeroGearOAuth2/OAuth2WebViewController.swift
generated
Normal file
@ -0,0 +1,53 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
import UIKit
|
||||
/**
|
||||
OAuth2WebViewController is a UIViewController to be used when the Oauth2 flow used an embedded view controller
|
||||
rather than an external browser approach.
|
||||
*/
|
||||
class OAuth2WebViewController: UIViewController, UIWebViewDelegate {
|
||||
/// Login URL for OAuth.
|
||||
var targetURL : NSURL = NSURL()
|
||||
/// WebView intance used to load login page.
|
||||
var webView : UIWebView = UIWebView()
|
||||
|
||||
/// Overrride of viewDidLoad to load the login page.
|
||||
override internal func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
webView.frame = UIScreen.mainScreen().applicationFrame
|
||||
webView.delegate = self
|
||||
self.view.addSubview(webView)
|
||||
loadAddressURL()
|
||||
}
|
||||
|
||||
override func viewDidLayoutSubviews() {
|
||||
super.viewDidLayoutSubviews()
|
||||
self.webView.frame = self.view.bounds
|
||||
}
|
||||
|
||||
override internal func didReceiveMemoryWarning() {
|
||||
super.didReceiveMemoryWarning()
|
||||
}
|
||||
|
||||
func loadAddressURL() {
|
||||
let req = NSURLRequest(URL: targetURL)
|
||||
webView.loadRequest(req)
|
||||
}
|
||||
}
|
||||
109
Pods/AeroGearOAuth2/AeroGearOAuth2/OpenIDClaim.swift
generated
Normal file
109
Pods/AeroGearOAuth2/AeroGearOAuth2/OpenIDClaim.swift
generated
Normal file
@ -0,0 +1,109 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Standard claims as described in spec: http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
|
||||
*/
|
||||
public class OpenIDClaim: CustomStringConvertible {
|
||||
/// Subject - Identifier for the End-User at the Issuer.
|
||||
public var sub: String?
|
||||
/// End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.
|
||||
public var name: String?
|
||||
/// Given name(s) or first name(s) of the End-User.
|
||||
public var givenName: String?
|
||||
/// Surname(s) or last name(s) of the End-User.
|
||||
public var familyName: String?
|
||||
/// Middle name(s) of the End-User.
|
||||
public var middleName: String?
|
||||
/// Casual name of the End-User that may or may not be the same as the given_name.
|
||||
public var nickname: String?
|
||||
/// Shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe.
|
||||
public var preferredUsername: String?
|
||||
/// URL of the End-User's profile page.
|
||||
public var profile: String?
|
||||
/// URL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), rather than to a Web page containing an image.
|
||||
public var picture: String?
|
||||
/// URL of the End-User's Web page or blog. This Web page SHOULD contain information published by the End-User or an organization that the End-User is affiliated with.
|
||||
public var website: String?
|
||||
/// End-User's preferred e-mail address.
|
||||
public var email: String?
|
||||
/// True if the End-User's e-mail address has been verified; otherwise false.
|
||||
public var emailVerified: Bool?
|
||||
/// End-User's gender. Values defined by this specification are female and male. Other values MAY be used when neither of the defined values are applicable.
|
||||
public var gender: String?
|
||||
/// End-User's birthday, represented as an ISO 8601:2004 [ISO8601‑2004] YYYY-MM-DD format.
|
||||
public var birthdate: String?
|
||||
/// String from zoneinfo [zoneinfo] time zone database representing the End-User's time zone. For example, Europe/Paris or America/Los_Angeles.
|
||||
public var zoneinfo: String?
|
||||
/// [ISO3166‑1] country code in uppercase, separated by a dash. For example, en-US or fr-CA.
|
||||
public var locale: String?
|
||||
/// End-User's preferred telephone number.
|
||||
public var phoneNumber: String?
|
||||
/// True if the End-User's phone number has been verified; otherwise false.
|
||||
public var phoneNumberVerified: Bool?
|
||||
/// End-User's preferred postal address.
|
||||
public var address: [String: AnyObject?]?
|
||||
/// Time the End-User's information was last updated.
|
||||
public var updatedAt: Int?
|
||||
// google specific - not in spec?
|
||||
public var kind: String?
|
||||
public var hd: String?
|
||||
/// Display all the claims.
|
||||
public var description: String {
|
||||
return "sub: \(sub)\nname: \(name)\ngivenName: \(givenName)\nfamilyName: \(familyName)\nmiddleName: \(middleName)\n" +
|
||||
"nickname: \(nickname)\npreferredUsername: \(preferredUsername)\nprofile: \(profile)\npicture: \(picture)\n" +
|
||||
"website: \(website)\nemail: \(email)\nemailVerified: \(emailVerified)\ngender: \(gender)\nbirthdate: \(birthdate)\n"
|
||||
}
|
||||
|
||||
/// Initialize an OpenIDClaim from a dictionary. all information not available are optional values set to .None.
|
||||
public init(fromDict:[String: AnyObject]) {
|
||||
sub = fromDict["sub"] as? String
|
||||
name = fromDict["name"] as? String
|
||||
givenName = fromDict["given_name"] as? String
|
||||
familyName = fromDict["family_name"] as? String
|
||||
middleName = fromDict["middle_name"] as? String
|
||||
nickname = fromDict["nickname"] as? String
|
||||
preferredUsername = fromDict["preferred_username"] as? String
|
||||
profile = fromDict["profile"] as? String
|
||||
picture = fromDict["picture"] as? String
|
||||
website = fromDict["website"] as? String
|
||||
email = fromDict["email"] as? String
|
||||
emailVerified = fromDict["email_verified"] as? Bool
|
||||
gender = fromDict["gender"] as? String
|
||||
zoneinfo = fromDict["zoneinfo"] as? String
|
||||
locale = fromDict["locale"] as? String
|
||||
phoneNumber = fromDict["phone_number"] as? String
|
||||
phoneNumberVerified = fromDict["phone_number_verified"] as? Bool
|
||||
updatedAt = fromDict["updated_at"] as? Int
|
||||
kind = fromDict["sub"] as? String
|
||||
hd = fromDict["hd"] as? String
|
||||
}
|
||||
}
|
||||
/// Facebook specific claims.
|
||||
public class FacebookOpenIDClaim: OpenIDClaim {
|
||||
|
||||
override init(fromDict:[String: AnyObject]) {
|
||||
super.init(fromDict: fromDict)
|
||||
givenName = fromDict["first_name"] as? String
|
||||
familyName = fromDict["last_name"] as? String
|
||||
zoneinfo = fromDict["timezone"] as? String
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
333
Pods/AeroGearOAuth2/AeroGearOAuth2/TrustedPersistantOAuth2Session.swift
generated
Normal file
333
Pods/AeroGearOAuth2/AeroGearOAuth2/TrustedPersistantOAuth2Session.swift
generated
Normal file
@ -0,0 +1,333 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import Foundation
|
||||
|
||||
import Security
|
||||
import UIKit
|
||||
|
||||
/**
|
||||
The type of token to be saved in KeychainWrap:
|
||||
|
||||
- AccessToken: access token
|
||||
- ExpirationDate: access token expiration date
|
||||
- RefreshToken: refresh token
|
||||
- RefreshExpirationDate: refresh token expiration date (used for Keycloak adapter only)
|
||||
*/
|
||||
public enum TokenType: String {
|
||||
case AccessToken = "AccessToken"
|
||||
case RefreshToken = "RefreshToken"
|
||||
case ExpirationDate = "ExpirationDate"
|
||||
case RefreshExpirationDate = "RefreshExpirationDate"
|
||||
}
|
||||
|
||||
/**
|
||||
A handy Keychain wrapper. It saves your OAuth2 tokens using WhenPasscodeSet ACL.
|
||||
*/
|
||||
public class KeychainWrap {
|
||||
|
||||
/**
|
||||
The service id. By default set to apple bundle id.
|
||||
*/
|
||||
public var serviceIdentifier: String
|
||||
|
||||
/**
|
||||
The group id is Keychain access group which is used for sharing keychain content accross multiple apps issued from same developer. By default there is no access group.
|
||||
*/
|
||||
public var groupId: String?
|
||||
|
||||
/**
|
||||
Initialize KeychainWrapper setting default values.
|
||||
|
||||
:param: serviceId unique service, defulated to bundleId
|
||||
:param: groupId used for SSO between app issued from same developer certificate.
|
||||
*/
|
||||
public init(serviceId: String? = NSBundle.mainBundle().bundleIdentifier, groupId: String? = nil) {
|
||||
if serviceId == nil {
|
||||
self.serviceIdentifier = "unkown"
|
||||
} else {
|
||||
self.serviceIdentifier = serviceId!
|
||||
}
|
||||
self.groupId = groupId
|
||||
}
|
||||
|
||||
/**
|
||||
Save tokens information in Keychain.
|
||||
|
||||
:param: key usually use accountId for oauth2 module, any unique string.
|
||||
:param: tokenType type of token: access, refresh.
|
||||
:param: value string value of the token.
|
||||
*/
|
||||
public func save(key: String, tokenType: TokenType, value: String) -> Bool {
|
||||
let dataFromString: NSData? = value.dataUsingEncoding(NSUTF8StringEncoding)
|
||||
if (dataFromString == nil) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Instantiate a new default keychain query
|
||||
let keychainQuery = NSMutableDictionary()
|
||||
if let groupId = self.groupId {
|
||||
keychainQuery[kSecAttrAccessGroup as String] = groupId
|
||||
}
|
||||
keychainQuery[kSecClass as String] = kSecClassGenericPassword
|
||||
keychainQuery[kSecAttrService as String] = self.serviceIdentifier
|
||||
keychainQuery[kSecAttrAccount as String] = key + "_" + tokenType.rawValue
|
||||
keychainQuery[kSecAttrAccessible as String] = kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
|
||||
|
||||
// Search for the keychain items
|
||||
let statusSearch: OSStatus = SecItemCopyMatching(keychainQuery, nil)
|
||||
|
||||
// if found update
|
||||
if (statusSearch == errSecSuccess) {
|
||||
if (dataFromString != nil) {
|
||||
let attributesToUpdate = NSMutableDictionary()
|
||||
attributesToUpdate[kSecValueData as String] = dataFromString!
|
||||
|
||||
let statusUpdate: OSStatus = SecItemUpdate(keychainQuery, attributesToUpdate)
|
||||
if (statusUpdate != errSecSuccess) {
|
||||
print("tokens not updated")
|
||||
return false
|
||||
}
|
||||
} else { // revoked token or newly installed app, clear KC
|
||||
return self.resetKeychain()
|
||||
}
|
||||
} else if(statusSearch == errSecItemNotFound) { // if new, add
|
||||
keychainQuery[kSecValueData as String] = dataFromString!
|
||||
let statusAdd: OSStatus = SecItemAdd(keychainQuery, nil)
|
||||
if(statusAdd != errSecSuccess) {
|
||||
print("tokens not saved")
|
||||
return false
|
||||
}
|
||||
} else { // error case
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
Read tokens information in Keychain. If the entry is not found return nil.
|
||||
|
||||
:param: userAccount key of the keychain entry, usually accountId for oauth2 module.
|
||||
:param: tokenType type of token: access, refresh.
|
||||
*/
|
||||
public func read(userAccount: String, tokenType: TokenType) -> String? {
|
||||
let keychainQuery = NSMutableDictionary()
|
||||
if let groupId = self.groupId {
|
||||
keychainQuery[kSecAttrAccessGroup as String] = groupId
|
||||
}
|
||||
keychainQuery[kSecClass as String] = kSecClassGenericPassword
|
||||
keychainQuery[kSecAttrService as String] = self.serviceIdentifier
|
||||
keychainQuery[kSecAttrAccount as String] = userAccount + "_" + tokenType.rawValue
|
||||
keychainQuery[kSecReturnData as String] = true
|
||||
keychainQuery[kSecAttrAccessible as String] = kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
|
||||
|
||||
|
||||
var dataTypeRef: Unmanaged<AnyObject>?
|
||||
// Search for the keychain items
|
||||
let status: OSStatus = withUnsafeMutablePointer(&dataTypeRef) { SecItemCopyMatching(keychainQuery as CFDictionaryRef, UnsafeMutablePointer($0)) }
|
||||
|
||||
if (status == errSecItemNotFound) {
|
||||
print("\(tokenType.rawValue) not found")
|
||||
return nil
|
||||
} else if (status != errSecSuccess) {
|
||||
print("Error attempting to retrieve \(tokenType.rawValue) with error code \(status) ")
|
||||
return nil
|
||||
}
|
||||
|
||||
let opaque = dataTypeRef?.toOpaque()
|
||||
var contentsOfKeychain: String?
|
||||
if let op = opaque {
|
||||
let retrievedData = Unmanaged<NSData>.fromOpaque(op).takeUnretainedValue()
|
||||
|
||||
// Convert the data retrieved from the keychain into a string
|
||||
contentsOfKeychain = NSString(data: retrievedData, encoding: NSUTF8StringEncoding) as? String
|
||||
} else {
|
||||
print("Nothing was retrieved from the keychain. Status code \(status)")
|
||||
}
|
||||
|
||||
return contentsOfKeychain
|
||||
}
|
||||
|
||||
/**
|
||||
Clear all keychain entries. Note that Keychain can only be cleared progemmatically.
|
||||
*/
|
||||
public func resetKeychain() -> Bool {
|
||||
return self.deleteAllKeysForSecClass(kSecClassGenericPassword) &&
|
||||
self.deleteAllKeysForSecClass(kSecClassInternetPassword) &&
|
||||
self.deleteAllKeysForSecClass(kSecClassCertificate) &&
|
||||
self.deleteAllKeysForSecClass(kSecClassKey) &&
|
||||
self.deleteAllKeysForSecClass(kSecClassIdentity)
|
||||
}
|
||||
|
||||
func deleteAllKeysForSecClass(secClass: CFTypeRef) -> Bool {
|
||||
let keychainQuery = NSMutableDictionary()
|
||||
keychainQuery[kSecClass as String] = secClass
|
||||
let result:OSStatus = SecItemDelete(keychainQuery)
|
||||
if (result == errSecSuccess) {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
An OAuth2Session implementation to store OAuth2 metadata using the Keychain.
|
||||
*/
|
||||
public class TrustedPersistantOAuth2Session: OAuth2Session {
|
||||
|
||||
/**
|
||||
The account id.
|
||||
*/
|
||||
public var accountId: String
|
||||
|
||||
/**
|
||||
The access token's expiration date.
|
||||
*/
|
||||
public var accessTokenExpirationDate: NSDate? {
|
||||
get {
|
||||
let dateAsString = self.keychain.read(self.accountId, tokenType: .ExpirationDate)
|
||||
if let unwrappedDate:String = dateAsString {
|
||||
return NSDate(dateString: unwrappedDate)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
set(value) {
|
||||
if let unwrappedValue = value {
|
||||
self.keychain.save(self.accountId, tokenType: .ExpirationDate, value: unwrappedValue.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
The access token. The information is read securely from Keychain.
|
||||
*/
|
||||
public var accessToken: String? {
|
||||
get {
|
||||
return self.keychain.read(self.accountId, tokenType: .AccessToken)
|
||||
}
|
||||
set(value) {
|
||||
if let unwrappedValue = value {
|
||||
self.keychain.save(self.accountId, tokenType: .AccessToken, value: unwrappedValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
The refresh token. The information is read securely from Keychain.
|
||||
*/
|
||||
public var refreshToken: String? {
|
||||
get {
|
||||
return self.keychain.read(self.accountId, tokenType: .RefreshToken)
|
||||
}
|
||||
set(value) {
|
||||
if let unwrappedValue = value {
|
||||
self.keychain.save(self.accountId, tokenType: .RefreshToken, value: unwrappedValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
The refresh token's expiration date.
|
||||
*/
|
||||
public var refreshTokenExpirationDate: NSDate? {
|
||||
get {
|
||||
let dateAsString = self.keychain.read(self.accountId, tokenType: .RefreshExpirationDate)
|
||||
if let unwrappedDate:String = dateAsString {
|
||||
return NSDate(dateString: unwrappedDate)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
set(value) {
|
||||
if let unwrappedValue = value {
|
||||
_ = self.keychain.save(self.accountId, tokenType: .RefreshExpirationDate, value: unwrappedValue.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private let keychain: KeychainWrap
|
||||
|
||||
/**
|
||||
Check validity of accessToken. return true if still valid, false when expired.
|
||||
*/
|
||||
public func tokenIsNotExpired() -> Bool {
|
||||
return self.accessTokenExpirationDate != nil ? (self.accessTokenExpirationDate!.timeIntervalSinceDate(NSDate()) > 0) : true
|
||||
}
|
||||
|
||||
/**
|
||||
Check validity of refreshToken. return true if still valid, false when expired.
|
||||
*/
|
||||
public func refreshTokenIsNotExpired() -> Bool {
|
||||
return self.refreshTokenExpirationDate != nil ? (self.refreshTokenExpirationDate!.timeIntervalSinceDate(NSDate()) > 0) : true
|
||||
}
|
||||
|
||||
/**
|
||||
Save in memory tokens information. Saving tokens allow you to refresh accesstoken transparently for the user without prompting for grant access.
|
||||
*/
|
||||
public func saveAccessToken(accessToken: String?, refreshToken: String?, accessTokenExpiration: String?, refreshTokenExpiration: String?) {
|
||||
self.accessToken = accessToken
|
||||
self.refreshToken = refreshToken
|
||||
|
||||
let now = NSDate()
|
||||
if let inter = accessTokenExpiration?.doubleValue {
|
||||
self.accessTokenExpirationDate = now.dateByAddingTimeInterval(inter)
|
||||
}
|
||||
if let inter = refreshTokenExpiration?.doubleValue {
|
||||
self.refreshTokenExpirationDate = now.dateByAddingTimeInterval(inter)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Clear all tokens. Method used when doing logout or revoke.
|
||||
*/
|
||||
public func clearTokens() {
|
||||
self.accessToken = nil
|
||||
self.refreshToken = nil
|
||||
self.accessTokenExpirationDate = nil
|
||||
self.refreshTokenExpirationDate = nil
|
||||
}
|
||||
|
||||
/**
|
||||
Initialize TrustedPersistantOAuth2Session using account id. Account id is the service id used for keychain storage.
|
||||
|
||||
:param: accountId uniqueId to identify the oauth2module
|
||||
:param: groupId used for SSO between app issued from same developer certificate.
|
||||
:param: accessToken optional parameter to initilaize the storage with initial values
|
||||
:param: accessTokenExpirationDate optional parameter to initilaize the storage with initial values
|
||||
:param: refreshToken optional parameter to initilaize the storage with initial values
|
||||
:param: refreshTokenExpirationDate optional parameter to initilaize the storage with initial values
|
||||
*/
|
||||
public init(accountId: String,
|
||||
groupId: String? = nil,
|
||||
accessToken: String? = nil,
|
||||
accessTokenExpirationDate: NSDate? = nil,
|
||||
refreshToken: String? = nil,
|
||||
refreshTokenExpirationDate: NSDate? = nil) {
|
||||
self.accountId = accountId
|
||||
if groupId != nil {
|
||||
self.keychain = KeychainWrap(serviceId: groupId, groupId: groupId)
|
||||
} else {
|
||||
self.keychain = KeychainWrap()
|
||||
}
|
||||
self.accessToken = accessToken
|
||||
self.refreshToken = refreshToken
|
||||
self.accessTokenExpirationDate = accessTokenExpirationDate
|
||||
self.refreshTokenExpirationDate = refreshTokenExpirationDate
|
||||
}
|
||||
}
|
||||
110
Pods/AeroGearOAuth2/AeroGearOAuth2/UntrustedMemoryOAuth2Session.swift
generated
Normal file
110
Pods/AeroGearOAuth2/AeroGearOAuth2/UntrustedMemoryOAuth2Session.swift
generated
Normal file
@ -0,0 +1,110 @@
|
||||
/*
|
||||
* JBoss, Home of Professional Open Source.
|
||||
* Copyright Red Hat, Inc., and individual contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import Foundation
|
||||
|
||||
extension String {
|
||||
var doubleValue: Double {
|
||||
return (self as NSString).doubleValue
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
An OAuth2Session implementation the stores OAuth2 metadata in-memory
|
||||
*/
|
||||
public class UntrustedMemoryOAuth2Session: OAuth2Session {
|
||||
|
||||
/**
|
||||
The account id.
|
||||
*/
|
||||
public var accountId: String
|
||||
|
||||
/**
|
||||
The access token which expires.
|
||||
*/
|
||||
public var accessToken: String?
|
||||
|
||||
/**
|
||||
The access token's expiration date.
|
||||
*/
|
||||
public var accessTokenExpirationDate: NSDate?
|
||||
|
||||
/**
|
||||
The refresh tokens. This toke does not expire and should be used to renew access token when expired.
|
||||
*/
|
||||
public var refreshToken: String?
|
||||
|
||||
/**
|
||||
The refresh token's expiration date.
|
||||
*/
|
||||
public var refreshTokenExpirationDate: NSDate?
|
||||
|
||||
/**
|
||||
Check validity of accessToken. return true if still valid, false when expired.
|
||||
*/
|
||||
public func tokenIsNotExpired() -> Bool {
|
||||
return self.accessTokenExpirationDate != nil ? (self.accessTokenExpirationDate!.timeIntervalSinceDate(NSDate()) > 0) : true
|
||||
}
|
||||
|
||||
/**
|
||||
Check validity of refreshToken. return true if still valid, false when expired.
|
||||
*/
|
||||
public func refreshTokenIsNotExpired() -> Bool {
|
||||
return self.refreshTokenExpirationDate != nil ? (self.refreshTokenExpirationDate!.timeIntervalSinceDate(NSDate()) > 0) : true
|
||||
}
|
||||
|
||||
/**
|
||||
Save in memory tokens information. Saving tokens allow you to refresh accesstoken transparently for the user without prompting for grant access.
|
||||
*/
|
||||
public func saveAccessToken(accessToken: String?, refreshToken: String?, accessTokenExpiration: String?, refreshTokenExpiration: String?) {
|
||||
self.accessToken = accessToken
|
||||
self.refreshToken = refreshToken
|
||||
let now = NSDate()
|
||||
if let inter = accessTokenExpiration?.doubleValue {
|
||||
self.accessTokenExpirationDate = now.dateByAddingTimeInterval(inter)
|
||||
}
|
||||
if let interRefresh = refreshTokenExpiration?.doubleValue {
|
||||
self.refreshTokenExpirationDate = now.dateByAddingTimeInterval(interRefresh)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Clear all tokens. Method used when doing logout or revoke.
|
||||
*/
|
||||
public func clearTokens() {
|
||||
self.accessToken = nil
|
||||
self.refreshToken = nil
|
||||
self.accessTokenExpirationDate = nil
|
||||
self.refreshTokenExpirationDate = nil
|
||||
}
|
||||
|
||||
/**
|
||||
Initialize session using account id.
|
||||
|
||||
:param: accountId uniqueId to identify the oauth2module.
|
||||
:param: accessToken optional parameter to initilaize the storage with initial values.
|
||||
:param: accessTokenExpirationDate optional parameter to initilaize the storage with initial values.
|
||||
:param: refreshToken optional parameter to initilaize the storage with initial values.
|
||||
:param: refreshTokenExpirationDate optional parameter to initilaize the storage with initial values.
|
||||
*/
|
||||
public init(accountId: String, accessToken: String? = nil, accessTokenExpirationDate: NSDate? = nil, refreshToken: String? = nil, refreshTokenExpirationDate: NSDate? = nil) {
|
||||
self.accessToken = accessToken
|
||||
self.accessTokenExpirationDate = accessTokenExpirationDate
|
||||
self.refreshToken = refreshToken
|
||||
self.refreshTokenExpirationDate = refreshTokenExpirationDate
|
||||
self.accountId = accountId
|
||||
}
|
||||
}
|
||||
202
Pods/AeroGearOAuth2/LICENSE.txt
generated
Normal file
202
Pods/AeroGearOAuth2/LICENSE.txt
generated
Normal file
@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
130
Pods/AeroGearOAuth2/README.md
generated
Normal file
130
Pods/AeroGearOAuth2/README.md
generated
Normal file
@ -0,0 +1,130 @@
|
||||
# aerogear-ios-oauth2 [](https://travis-ci.org/aerogear/aerogear-ios-oauth2)
|
||||
|
||||
> This module currently build with Xcode 7 and supports iOS8, iOS9.
|
||||
|
||||
OAuth2 Client based on [aerogear-ios-http](https://github.com/aerogear/aerogear-ios-http).
|
||||
Taking care of:
|
||||
|
||||
* account manager for multiple OAuth2 accounts,
|
||||
* request access and refresh token,
|
||||
* grant access through secure external browser and URI schema to re-enter app,
|
||||
* (implicit or explicit) refresh tokens,
|
||||
* revoke tokens,
|
||||
* permanent secure storage,
|
||||
* adaptable to OAuth2 specific providers. Existing extensions: Google, Facebook, [Keycloak 1.5.0.Final](http://keycloak.jboss.org/) etc...
|
||||
* openID Connect login
|
||||
|
||||
100% Swift 2.0.
|
||||
|
||||
| | Project Info |
|
||||
| --------------- | ------------- |
|
||||
| License: | Apache License, Version 2.0 |
|
||||
| Build: | CocoaPods |
|
||||
| Documentation: | https://aerogear.org/docs/guides/aerogear-ios-2.X/ |
|
||||
| Issue tracker: | https://issues.jboss.org/browse/AGIOS |
|
||||
| Mailing lists: | [aerogear-users](http://aerogear-users.1116366.n5.nabble.com/) ([subscribe](https://lists.jboss.org/mailman/listinfo/aerogear-users)) |
|
||||
| | [aerogear-dev](http://aerogear-dev.1069024.n5.nabble.com/) ([subscribe](https://lists.jboss.org/mailman/listinfo/aerogear-dev)) |
|
||||
|
||||
## Example Usage
|
||||
|
||||
#### OAuth2 grant for GET with a predefined config like Facebook
|
||||
```swift
|
||||
var Http = Http() // [1]
|
||||
let facebookConfig = FacebookConfig( // [2]
|
||||
clientId: "YYY",
|
||||
clientSecret: "XXX",
|
||||
scopes:["photo_upload, publish_actions"])
|
||||
var oauth2Module = AccountManager.addFacebookAccount(facebookConfig) // [3]
|
||||
http.authzModule = oauth2Module // [4]
|
||||
http.request(.GET, path: "/get", completionHandler: {(response, error) in // [5]
|
||||
// handle response
|
||||
})
|
||||
```
|
||||
Create an instance of Http [1] from [aerogear-ios-http](https://github.com/aerogear/aerogear-ios-http) a thin layer on top of NSURLSession.
|
||||
|
||||
Fill-in the OAuth2 configuration in [2], here we use a predefined Config with all Facebook endpoint filled-in for us.
|
||||
|
||||
Create an OAuth2Module from AccountManager's factory method in [3].
|
||||
|
||||
Inject OAuth2Module into http object in [4] and uses the http object to GET/POST etc...
|
||||
|
||||
See full description in [aerogear.org](https://aerogear.org/docs/guides/aerogear-ios-2.X/Authorization/)
|
||||
|
||||
#### OpenID Connect with Keycloak
|
||||
```swift
|
||||
var Http = Http()
|
||||
let keycloakConfig = KeycloakConfig(
|
||||
clientId: "sharedshoot-third-party",
|
||||
host: "http://localhost:8080",
|
||||
realm: "shoot-realm",
|
||||
isOpenIDConnect: true)
|
||||
var oauth2Module = AccountManager.addKeycloakAccount(keycloakConfig)
|
||||
http.authzModule = oauth2Module
|
||||
oauth2Module.login {(accessToken: AnyObject?, claims: OpenIDClaim?, error: NSError?) in // [1]
|
||||
// Do your own stuff here
|
||||
}
|
||||
|
||||
```
|
||||
Similar approach for configuration, here we want to login as Keycloak user, using ```login``` method we get some user information back in OpenIDClaim object.
|
||||
|
||||
> **NOTE:** The latest version of the library works with Keycloak 1.1.0.Final. Previous version of Keycloak 1.0.x will work except for the transparent refresh of tokens (ie: after access token expires you will have to go through grant process).
|
||||
|
||||
### Build, test and play with aerogear-ios-oauth2
|
||||
|
||||
1. Clone this project
|
||||
|
||||
2. Get the dependencies
|
||||
|
||||
The project uses [CocoaPods](http://cocoapods.org) for handling its dependencies. As a pre-requisite, install CocoaPods and then install the pod. On the root directory of the project run:
|
||||
```bash
|
||||
pod install
|
||||
```
|
||||
3. open AeroGearOAuth2.xcworkspace
|
||||
|
||||
## Adding the library to your project
|
||||
To add the library in your project, you can either use [CocoaPods](http://cocoapods.org) or manual install in your project. See the respective sections below for instructions:
|
||||
|
||||
### Using [CocoaPods](http://cocoapods.org)
|
||||
In your ```Podfile``` add:
|
||||
|
||||
```
|
||||
pod 'AeroGearOAuth2'
|
||||
```
|
||||
|
||||
and then:
|
||||
|
||||
```bash
|
||||
pod install
|
||||
```
|
||||
|
||||
to install your dependencies
|
||||
|
||||
### Manual Installation
|
||||
Follow these steps to add the library in your Swift project:
|
||||
|
||||
1. Add AeroGearOAuth2 as a [submodule](http://git-scm.com/docs/git-submodule) in your project. Open a terminal and navigate to your project directory. Then enter:
|
||||
```bash
|
||||
git submodule add https://github.com/aerogear/aerogear-ios-oauth2.git
|
||||
```
|
||||
2. Open the `aerogear-ios-oauth2` folder, and drag the `AeroGearOAuth2.xcodeproj` into the file navigator in Xcode.
|
||||
3. In Xcode select your application target and under the "Targets" heading section, ensure that the 'iOS Deployment Target' matches the application target of AeroGearOAuth2.framework (Currently set to 8.0).
|
||||
5. Select the "Build Phases" heading section, expand the "Target Dependencies" group and add `AeroGearOAuth2.framework`.
|
||||
7. Click on the `+` button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add `AeroGearOAuth2.framework`.
|
||||
|
||||
## Documentation
|
||||
|
||||
For more details about the current release, please consult [our documentation](https://aerogear.org/docs/guides/aerogear-ios-2.X/).
|
||||
|
||||
## Development
|
||||
|
||||
If you would like to help develop AeroGear you can join our [developer's mailing list](https://lists.jboss.org/mailman/listinfo/aerogear-dev), join #aerogear on Freenode, or shout at us on Twitter @aerogears.
|
||||
|
||||
Also takes some time and skim the [contributor guide](http://aerogear.org/docs/guides/Contributing/)
|
||||
|
||||
## Questions?
|
||||
|
||||
Join our [user mailing list](https://lists.jboss.org/mailman/listinfo/aerogear-users) for any questions or help! We really hope you enjoy app development with AeroGear!
|
||||
|
||||
## Found a bug?
|
||||
|
||||
If you found a bug please create a ticket for us on [Jira](https://issues.jboss.org/browse/AGIOS) with some steps to reproduce it.
|
||||
202
Pods/GDataXML-HTML/LICENSE
generated
Normal file
202
Pods/GDataXML-HTML/LICENSE
generated
Normal file
@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
245
Pods/GDataXML-HTML/Pod/Classes/GDataXMLNode.h
generated
Normal file
245
Pods/GDataXML-HTML/Pod/Classes/GDataXMLNode.h
generated
Normal file
@ -0,0 +1,245 @@
|
||||
/* Modifications for HTML parser support:
|
||||
* Copyright (c) 2011 Simon Grätzer simon@graetzer.org
|
||||
*
|
||||
* Copyright (c) 2008 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// These node, element, and document classes implement a subset of the methods
|
||||
// provided by NSXML. While NSXML behavior is mimicked as much as possible,
|
||||
// there are important differences.
|
||||
//
|
||||
// The biggest difference is that, since this is based on libxml2, there
|
||||
// is no retain model for the underlying node data. Rather than copy every
|
||||
// node obtained from a parse tree (which would have a substantial memory
|
||||
// impact), we rely on weak references, and it is up to the code that
|
||||
// created a document to retain it for as long as any
|
||||
// references rely on nodes inside that document tree.
|
||||
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
// libxml includes require that the target Header Search Paths contain
|
||||
//
|
||||
// /usr/include/libxml2
|
||||
//
|
||||
// and Other Linker Flags contain
|
||||
//
|
||||
// -lxml2
|
||||
|
||||
#import <libxml/tree.h>
|
||||
#import <libxml/parser.h>
|
||||
#import <libxml/xmlstring.h>
|
||||
#import <libxml/HTMLparser.h>
|
||||
#import <libxml/xpath.h>
|
||||
#import <libxml/xpathInternals.h>
|
||||
|
||||
|
||||
#if (MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4) || defined(GDATA_TARGET_NAMESPACE)
|
||||
// we need NSInteger for the 10.4 SDK, or we're using target namespace macros
|
||||
#import "GDataDefines.h"
|
||||
#endif
|
||||
|
||||
#undef _EXTERN
|
||||
#undef _INITIALIZE_AS
|
||||
#ifdef GDATAXMLNODE_DEFINE_GLOBALS
|
||||
#define _EXTERN
|
||||
#define _INITIALIZE_AS(x) =x
|
||||
#else
|
||||
#if defined(__cplusplus)
|
||||
#define _EXTERN extern "C"
|
||||
#else
|
||||
#define _EXTERN extern
|
||||
#endif
|
||||
#define _INITIALIZE_AS(x)
|
||||
#endif
|
||||
|
||||
// when no namespace dictionary is supplied for XPath, the default namespace
|
||||
// for the evaluated tree is registered with the prefix _def_ns
|
||||
_EXTERN const char* kGDataXMLXPathDefaultNamespacePrefix _INITIALIZE_AS("_def_ns");
|
||||
|
||||
// Nomenclature for method names:
|
||||
//
|
||||
// Node = GData node
|
||||
// XMLNode = xmlNodePtr
|
||||
//
|
||||
// So, for example:
|
||||
// + (id)nodeConsumingXMLNode:(xmlNodePtr)theXMLNode;
|
||||
|
||||
@class NSArray, NSDictionary, NSError, NSString, NSURL;
|
||||
@class GDataXMLElement, GDataXMLDocument;
|
||||
|
||||
enum {
|
||||
GDataXMLInvalidKind = 0,
|
||||
GDataXMLDocumentKind,
|
||||
GDataXMLElementKind,
|
||||
GDataXMLAttributeKind,
|
||||
GDataXMLNamespaceKind,
|
||||
GDataXMLProcessingInstructionKind,
|
||||
GDataXMLCommentKind,
|
||||
GDataXMLTextKind,
|
||||
GDataXMLDTDKind,
|
||||
GDataXMLEntityDeclarationKind,
|
||||
GDataXMLAttributeDeclarationKind,
|
||||
GDataXMLElementDeclarationKind,
|
||||
GDataXMLNotationDeclarationKind
|
||||
};
|
||||
|
||||
typedef NSUInteger GDataXMLNodeKind;
|
||||
|
||||
@interface GDataXMLNode : NSObject <NSCopying> {
|
||||
@protected
|
||||
// NSXMLNodes can have a namespace URI or prefix even if not part
|
||||
// of a tree; xmlNodes cannot. When we create nodes apart from
|
||||
// a tree, we'll store the dangling prefix or URI in the xmlNode's name,
|
||||
// like
|
||||
// "prefix:name"
|
||||
// or
|
||||
// "{http://uri}:name"
|
||||
//
|
||||
// We will fix up the node's namespace and name (and those of any children)
|
||||
// later when adding the node to a tree with addChild: or addAttribute:.
|
||||
// See fixUpNamespacesForNode:.
|
||||
|
||||
xmlNodePtr xmlNode_; // may also be an xmlAttrPtr or xmlNsPtr
|
||||
BOOL shouldFreeXMLNode_; // if yes, xmlNode_ will be free'd in dealloc
|
||||
|
||||
// cached values
|
||||
NSString *cachedName_;
|
||||
NSArray *cachedChildren_;
|
||||
NSArray *cachedAttributes_;
|
||||
}
|
||||
|
||||
+ (GDataXMLElement *)elementWithName:(NSString *)name;
|
||||
+ (GDataXMLElement *)elementWithName:(NSString *)name stringValue:(NSString *)value;
|
||||
+ (GDataXMLElement *)elementWithName:(NSString *)name URI:(NSString *)value;
|
||||
|
||||
+ (id)attributeWithName:(NSString *)name stringValue:(NSString *)value;
|
||||
+ (id)attributeWithName:(NSString *)name URI:(NSString *)attributeURI stringValue:(NSString *)value;
|
||||
|
||||
+ (id)namespaceWithName:(NSString *)name stringValue:(NSString *)value;
|
||||
|
||||
+ (id)textWithStringValue:(NSString *)value;
|
||||
|
||||
- (NSString *)stringValue;
|
||||
- (void)setStringValue:(NSString *)str;
|
||||
|
||||
- (NSUInteger)childCount;
|
||||
- (NSArray *)children;
|
||||
- (GDataXMLNode *)childAtIndex:(unsigned)index;
|
||||
|
||||
- (NSString *)localName;
|
||||
- (NSString *)name;
|
||||
- (NSString *)prefix;
|
||||
- (NSString *)URI;
|
||||
|
||||
- (GDataXMLNodeKind)kind;
|
||||
|
||||
- (NSString *)XMLString;
|
||||
|
||||
+ (NSString *)localNameForName:(NSString *)name;
|
||||
+ (NSString *)prefixForName:(NSString *)name;
|
||||
|
||||
// This is the preferred entry point for nodesForXPath. This takes an explicit
|
||||
// namespace dictionary (keys are prefixes, values are URIs).
|
||||
- (NSArray *)nodesForXPath:(NSString *)xpath namespaces:(NSDictionary *)namespaces error:(NSError **)error;
|
||||
|
||||
- (GDataXMLNode *)firstNodeForXPath:(NSString *)xpath namespaces:(NSDictionary *)namespaces error:(NSError **)error;
|
||||
|
||||
// This implementation of nodesForXPath registers namespaces only from the
|
||||
// document's root node. _def_ns may be used as a prefix for the default
|
||||
// namespace, though there's no guarantee that the default namespace will
|
||||
// be consistenly the same namespace in server responses.
|
||||
- (NSArray *)nodesForXPath:(NSString *)xpath error:(NSError **)error;
|
||||
|
||||
- (GDataXMLNode *)firstNodeForXPath:(NSString *)xpath error:(NSError **)error;
|
||||
|
||||
// access to the underlying libxml node; be sure to release the cached values
|
||||
// if you change the underlying tree at all
|
||||
- (xmlNodePtr)XMLNode;
|
||||
- (void)releaseCachedValues;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@interface GDataXMLElement : GDataXMLNode
|
||||
|
||||
- (id)initWithXMLString:(NSString *)str error:(NSError **)error;
|
||||
- (id)initWithHTMLString:(NSString *)str error:(NSError **)error;
|
||||
|
||||
- (NSArray *)namespaces;
|
||||
- (void)setNamespaces:(NSArray *)namespaces;
|
||||
- (void)addNamespace:(GDataXMLNode *)aNamespace;
|
||||
|
||||
// addChild adds a copy of the child node to the element
|
||||
- (void)addChild:(GDataXMLNode *)child;
|
||||
- (void)removeChild:(GDataXMLNode *)child;
|
||||
|
||||
- (NSArray *)elementsForName:(NSString *)name;
|
||||
- (NSArray *)elementsForLocalName:(NSString *)localName URI:(NSString *)URI;
|
||||
|
||||
- (NSArray *)attributes;
|
||||
- (GDataXMLNode *)attributeForName:(NSString *)name;
|
||||
- (GDataXMLNode *)attributeForLocalName:(NSString *)name URI:(NSString *)attributeURI;
|
||||
- (void)addAttribute:(GDataXMLNode *)attribute;
|
||||
|
||||
- (NSString *)resolvePrefixForNamespaceURI:(NSString *)namespaceURI;
|
||||
|
||||
@end
|
||||
|
||||
@interface GDataXMLDocument : NSObject {
|
||||
@protected
|
||||
xmlDoc* xmlDoc_; // strong; always free'd in dealloc
|
||||
NSStringEncoding _encoding;
|
||||
}
|
||||
|
||||
- (id)initWithXMLString:(NSString *)str encoding:(NSStringEncoding)encoding error:(NSError **)error;
|
||||
- (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding error:(NSError **)error;
|
||||
|
||||
- (id)initWithHTMLString:(NSString *)str encoding:(NSStringEncoding)encoding error:(NSError **)error;
|
||||
- (id)initWithHTMLData:(NSData *)data encoding:(NSStringEncoding)encoding error:(NSError **)error;
|
||||
|
||||
- (id)initWithXMLString:(NSString *)str error:(NSError **)error;
|
||||
- (id)initWithData:(NSData *)data error:(NSError **)error;
|
||||
|
||||
- (id)initWithHTMLString:(NSString *)str error:(NSError **)error;
|
||||
- (id)initWithHTMLData:(NSData *)data error:(NSError **)error;
|
||||
|
||||
// initWithRootElement uses a copy of the argument as the new document's root
|
||||
- (id)initWithRootElement:(GDataXMLElement *)element;
|
||||
|
||||
- (GDataXMLElement *)rootElement;
|
||||
|
||||
- (NSData *)XMLData;
|
||||
|
||||
- (void)setVersion:(NSString *)version;
|
||||
- (void)setCharacterEncoding:(NSString *)encoding;
|
||||
|
||||
// This is the preferred entry point for nodesForXPath. This takes an explicit
|
||||
// namespace dictionary (keys are prefixes, values are URIs).
|
||||
- (NSArray *)nodesForXPath:(NSString *)xpath namespaces:(NSDictionary *)namespaces error:(NSError **)error;
|
||||
|
||||
// Convenience method returns first element with speciifed xpath or nil
|
||||
- (GDataXMLNode *)firstNodeForXPath:(NSString *)xpath namespaces:(NSDictionary *)namespaces error:(NSError **)error;
|
||||
|
||||
// This implementation of nodesForXPath registers namespaces only from the
|
||||
// document's root node. _def_ns may be used as a prefix for the default
|
||||
// namespace, though there's no guarantee that the default namespace will
|
||||
// be consistenly the same namespace in server responses.
|
||||
- (NSArray *)nodesForXPath:(NSString *)xpath error:(NSError **)error;
|
||||
|
||||
- (GDataXMLNode *)firstNodeForXPath:(NSString *)xpath error:(NSError **)error;
|
||||
|
||||
- (NSString *)description;
|
||||
@end
|
||||
2012
Pods/GDataXML-HTML/Pod/Classes/GDataXMLNode.m
generated
Normal file
2012
Pods/GDataXML-HTML/Pod/Classes/GDataXMLNode.m
generated
Normal file
File diff suppressed because it is too large
Load Diff
58
Pods/GDataXML-HTML/README.md
generated
Normal file
58
Pods/GDataXML-HTML/README.md
generated
Normal file
@ -0,0 +1,58 @@
|
||||
# Description #
|
||||
|
||||
[](http://cocoadocs.org/docsets/GDataXML-HTML/)
|
||||
[](http://cocoadocs.org/docsets/GDataXML-HTML/)
|
||||
[](https://travis-ci.org/graetzer/GDataXML-HTML)
|
||||
|
||||
GDataXML-HTML is a HTML/XML parser for iOS and OSX, based on Google's GDataXML. As the name suggest it adds support for the HTMLparser module of libxml2 and enables you to deal with non validating XML or HTML.
|
||||
|
||||
So you can use e.g. XPath to parse Websites with reasonable performance
|
||||
|
||||
# Use in your own project #
|
||||
|
||||
### Install with CocoaPods
|
||||
|
||||
pod 'GDataXML-HTML', '~> 1.3.0'
|
||||
|
||||
### Manually ###
|
||||
|
||||
1. First add the files from the Pod/Classes folder in this project to your source tree, then include them somewhere in your code,
|
||||
|
||||
2. In Xcode choose the project file (in the project navigator, the top item).
|
||||
|
||||
3. In the list choose your project target and select 'Build Settings' at the top of the window.
|
||||
Then you should see a list of build options.
|
||||
|
||||
4. Add this line to 'Header Search Paths' (use search bar to find the right option)
|
||||
/usr/include/libxml2
|
||||
|
||||
5. Add this line to 'Other Linker Flags':
|
||||
-lxml2
|
||||
|
||||
# Examples #
|
||||
There are usage examples inside the GDataXML_HTMLViewController.m file.
|
||||
|
||||
### Other examples for GDataXML on the web: ###
|
||||
|
||||
1. http://www.raywenderlich.com/725/how-to-read-and-write-xml-documents-with-gdataxml
|
||||
|
||||
2. http://dubydigital.com/iphone/?p=59
|
||||
|
||||
# Licence #
|
||||
Original GDataXML:
|
||||
Copyright (c) 2008 Google Inc
|
||||
|
||||
Example project and HTML addons:
|
||||
Copyright (c) 2012-2014 Simon Grätzer
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
5
Pods/GDataXML-HTML/libxml.modulemap
generated
Normal file
5
Pods/GDataXML-HTML/libxml.modulemap
generated
Normal file
@ -0,0 +1,5 @@
|
||||
module libxml [system] {
|
||||
header "/usr/include/libxml2/libxml/tree.h"
|
||||
link "libxml"
|
||||
export *
|
||||
}
|
||||
50
Pods/Manifest.lock
generated
50
Pods/Manifest.lock
generated
@ -1,4 +1,28 @@
|
||||
PODS:
|
||||
- AeroGearHttp (0.6.0)
|
||||
- AeroGearOAuth2 (0.5.1):
|
||||
- AeroGearHttp
|
||||
- AFNetworking (2.6.3):
|
||||
- AFNetworking/NSURLConnection (= 2.6.3)
|
||||
- AFNetworking/NSURLSession (= 2.6.3)
|
||||
- AFNetworking/Reachability (= 2.6.3)
|
||||
- AFNetworking/Security (= 2.6.3)
|
||||
- AFNetworking/Serialization (= 2.6.3)
|
||||
- AFNetworking/UIKit (= 2.6.3)
|
||||
- AFNetworking/NSURLConnection (2.6.3):
|
||||
- AFNetworking/Reachability
|
||||
- AFNetworking/Security
|
||||
- AFNetworking/Serialization
|
||||
- AFNetworking/NSURLSession (2.6.3):
|
||||
- AFNetworking/Reachability
|
||||
- AFNetworking/Security
|
||||
- AFNetworking/Serialization
|
||||
- AFNetworking/Reachability (2.6.3)
|
||||
- AFNetworking/Security (2.6.3)
|
||||
- AFNetworking/Serialization (2.6.3)
|
||||
- AFNetworking/UIKit (2.6.3):
|
||||
- AFNetworking/NSURLConnection
|
||||
- AFNetworking/NSURLSession
|
||||
- Alamofire (3.4.1)
|
||||
- Alamofire-SwiftyJSON (0.1.1):
|
||||
- Alamofire (~> 3.4)
|
||||
@ -47,6 +71,7 @@ PODS:
|
||||
- FirebaseStorage (1.0.2):
|
||||
- FirebaseAnalytics (~> 3.2)
|
||||
- GoogleNetworkingUtilities (~> 1.2)
|
||||
- GDataXML-HTML (1.3.0)
|
||||
- GoogleInterchangeUtilities (1.2.1):
|
||||
- GoogleSymbolUtilities (~> 1.0)
|
||||
- GoogleNetworkingUtilities (1.2.1):
|
||||
@ -59,27 +84,46 @@ PODS:
|
||||
- GoogleSymbolUtilities (~> 1.0)
|
||||
- Locksmith (2.0.8)
|
||||
- OAuthSwift (0.5.2)
|
||||
- PicoKit (0.7.2):
|
||||
- PicoKit/WebService (= 0.7.2)
|
||||
- PicoKit/Core (0.7.2):
|
||||
- GDataXML-HTML (~> 1.3.0)
|
||||
- PicoKit/OrderedDictionary
|
||||
- PicoKit/XMLWriter
|
||||
- PicoKit/OrderedDictionary (0.7.2)
|
||||
- PicoKit/Soap (0.7.2):
|
||||
- PicoKit/Core
|
||||
- PicoKit/WebService (0.7.2):
|
||||
- AFNetworking (~> 2.6.0)
|
||||
- PicoKit/Soap
|
||||
- PicoKit/XMLWriter (0.7.2)
|
||||
- SwiftyJSON (2.3.2)
|
||||
- SWRevealViewController (2.3.0)
|
||||
- TYMActivityIndicatorView (0.3.3)
|
||||
- UIImageViewModeScaleAspect (1.5)
|
||||
|
||||
DEPENDENCIES:
|
||||
- AeroGearHttp
|
||||
- AeroGearOAuth2
|
||||
- Alamofire-SwiftyJSON
|
||||
- BSImagePicker (~> 2.3)
|
||||
- FBSDKCoreKit
|
||||
- FBSDKLoginKit
|
||||
- FBSDKShareKit
|
||||
- Firebase (>= 2.5.0)
|
||||
- Firebase
|
||||
- Firebase/Database
|
||||
- Firebase/Storage
|
||||
- FirebaseAuth
|
||||
- Locksmith
|
||||
- OAuthSwift (~> 0.5.0)
|
||||
- PicoKit
|
||||
- SWRevealViewController
|
||||
- TYMActivityIndicatorView
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
AeroGearHttp: e958f301cc2d1c7fbfd4b61af187ea3490040a48
|
||||
AeroGearOAuth2: 6f29d3fac8b78a0ff6d51b04c4ba1a02baed2e52
|
||||
AFNetworking: cb8d14a848e831097108418f5d49217339d4eb60
|
||||
Alamofire: 01a82e2f6c0f860ade35534c8dd88be61bdef40c
|
||||
Alamofire-SwiftyJSON: 5812bb37accc36897cc2f2dabb070d8ebcd7ac98
|
||||
Bolts: 8a7995239dbe724f9cba2248b766d48b7ebdd322
|
||||
@ -94,6 +138,7 @@ SPEC CHECKSUMS:
|
||||
FirebaseDatabase: 59bea2e7dfd81b3b8b2f8e396caf1a52c2ced6f7
|
||||
FirebaseInstanceID: ba1e640935235e5fac39dfa816fe7660e72e1a8a
|
||||
FirebaseStorage: fa2a87dee81f682f553af6839daa37a750e65f6a
|
||||
GDataXML-HTML: 7adc03668cab35c288f1dbb8929a179f0fece898
|
||||
GoogleInterchangeUtilities: def8415a862effc67d549d5b5b0b9c7a2f97d4de
|
||||
GoogleNetworkingUtilities: 3e83269048cfb498dc7ec83ab36813360965c74f
|
||||
GoogleParsingUtilities: 30b3896f9ee167dc78747f013d3de157ced1cadf
|
||||
@ -101,11 +146,12 @@ SPEC CHECKSUMS:
|
||||
GoogleUtilities: 56c5ac05b7aa5dc417a1bb85221a9516e04d7032
|
||||
Locksmith: a8ed41ac4c06506ea8cb199d8ec8a8d3d108eb2a
|
||||
OAuthSwift: 1ef042d4362e755e24a78f158d817245641a5d24
|
||||
PicoKit: 9079bce659a8d5408c8af1c45254b971df614de3
|
||||
SwiftyJSON: 04ccea08915aa0109039157c7974cf0298da292a
|
||||
SWRevealViewController: 6d3fd97f70112fd7cef9de14df4260eacce4c63a
|
||||
TYMActivityIndicatorView: ad816387ebd5952c376af129218722733044148b
|
||||
UIImageViewModeScaleAspect: 11a790a0b9d248a13dc63e3a78991f1463b6d84e
|
||||
|
||||
PODFILE CHECKSUM: f0e94f082ecd182e6ea530edddd9bc1c1cb65997
|
||||
PODFILE CHECKSUM: 3b36a7c734809ee54f4ecf0055d9910a9279d555
|
||||
|
||||
COCOAPODS: 1.0.0
|
||||
|
||||
22
Pods/PicoKit/LICENSE
generated
Normal file
22
Pods/PicoKit/LICENSE
generated
Normal file
@ -0,0 +1,22 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2013 Leansoft Technology 51startup@sina.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
26
Pods/PicoKit/Pod/Core/Cache/PicoCache.h
generated
Normal file
26
Pods/PicoKit/Pod/Core/Cache/PicoCache.h
generated
Normal file
@ -0,0 +1,26 @@
|
||||
//
|
||||
// PicoCache.h
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-25.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
@interface PicoCache : NSObject {
|
||||
@private
|
||||
NSUInteger _countLimit;
|
||||
|
||||
}
|
||||
|
||||
@property (nonatomic, assign, readwrite) NSUInteger countLimit;
|
||||
|
||||
- (instancetype) initWithCountLimit : (NSUInteger) limit NS_DESIGNATED_INITIALIZER;
|
||||
- (id) objectForKey: (id)key;
|
||||
- (void) setObject: (id)object forKey:(id)key;
|
||||
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSArray *allKeys;
|
||||
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSArray *allValues;
|
||||
- (void)removeObjectForKey:(id)key;
|
||||
- (void)removeAllObjects;
|
||||
@property (NS_NONATOMIC_IOSONLY, readonly) NSUInteger count;
|
||||
|
||||
@end
|
||||
141
Pods/PicoKit/Pod/Core/Cache/PicoCache.m
generated
Normal file
141
Pods/PicoKit/Pod/Core/Cache/PicoCache.m
generated
Normal file
@ -0,0 +1,141 @@
|
||||
//
|
||||
// PicoCache.m
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-25.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#import "PicoCache.h"
|
||||
#import "PicoCacheEntry.h"
|
||||
|
||||
@interface PicoCache () {
|
||||
@private
|
||||
NSMutableDictionary *_entries;
|
||||
NSMutableArray *_entriesByTime;
|
||||
}
|
||||
|
||||
@property (strong, nonatomic) NSMutableDictionary *entries;
|
||||
@property (strong, nonatomic) NSMutableArray *entriesByTime;
|
||||
|
||||
- (void)evictObjectsExceedingCountLimit;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation PicoCache
|
||||
|
||||
@synthesize entries = _entries, entriesByTime = _entriesByTime;
|
||||
|
||||
@synthesize countLimit = _countLimit;
|
||||
|
||||
- (instancetype)init {
|
||||
return [self initWithCountLimit:0];
|
||||
}
|
||||
|
||||
- (instancetype)initWithCountLimit:(NSUInteger)limit {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_entries = [[NSMutableDictionary alloc] init];
|
||||
_entriesByTime = [[NSMutableArray alloc] init];
|
||||
|
||||
_countLimit = limit;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (id)objectForKey:(id)key {
|
||||
if (!key) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
@synchronized(self) {
|
||||
// Look for the cache entry with the given key
|
||||
PicoCacheEntry *entry = _entries[key];
|
||||
if (!entry) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
// Refresh the entry by moving it to the end of the LRU list
|
||||
[_entriesByTime removeObjectIdenticalTo:entry];
|
||||
[_entriesByTime addObject: entry];
|
||||
|
||||
return [entry object];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setObject:(id)object forKey:(id)key {
|
||||
if (!object || !key) {
|
||||
return;
|
||||
}
|
||||
|
||||
@synchronized(self) {
|
||||
PicoCacheEntry *entry = _entries[key];
|
||||
if (entry) {
|
||||
// Object exists in cache, refresh by removing it from the list
|
||||
[_entriesByTime removeObjectIdenticalTo:entry];
|
||||
[_entries removeObjectForKey:key];
|
||||
}
|
||||
|
||||
// Create a cache entry to contain the given object
|
||||
entry = [[PicoCacheEntry alloc] initWithObject:object forKey:key];
|
||||
|
||||
// Add the entry to the cache and put it at the end of the LRU list
|
||||
_entries[key] = entry;
|
||||
[_entriesByTime addObject:entry];
|
||||
|
||||
// Enforce the count limit
|
||||
[self evictObjectsExceedingCountLimit];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
- (NSArray *)allKeys {
|
||||
return [_entries allKeys];
|
||||
}
|
||||
|
||||
- (NSArray *)allValues {
|
||||
NSMutableArray *values = [NSMutableArray arrayWithCapacity:[_entries count]];
|
||||
for (PicoCacheEntry *entry in [_entries allValues]) {
|
||||
[values addObject:[entry object]];
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
- (void)removeObjectForKey:(id)key {
|
||||
PicoCacheEntry *entry = _entries[key];
|
||||
if (entry) {
|
||||
[_entries removeObjectForKey:key];
|
||||
[_entriesByTime removeObjectIdenticalTo:entry];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)removeAllObjects {
|
||||
[_entries removeAllObjects];
|
||||
[_entriesByTime removeAllObjects];
|
||||
}
|
||||
|
||||
- (NSUInteger)count {
|
||||
return [_entries count];
|
||||
}
|
||||
|
||||
- (void)evictObjectsExceedingCountLimit {
|
||||
if (_countLimit == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
NSUInteger count = [_entriesByTime count];
|
||||
if (count == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Remove oldest entries that exceed the count limit
|
||||
for(NSUInteger i = count; i > _countLimit; i--) {
|
||||
PicoCacheEntry *entry = _entriesByTime[0];
|
||||
[_entries removeObjectForKey:[entry key]];
|
||||
[_entriesByTime removeObjectAtIndex:0];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@end
|
||||
22
Pods/PicoKit/Pod/Core/Cache/PicoCacheEntry.h
generated
Normal file
22
Pods/PicoKit/Pod/Core/Cache/PicoCacheEntry.h
generated
Normal file
@ -0,0 +1,22 @@
|
||||
//
|
||||
// PicoCacheEntry.h
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-25.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
@interface PicoCacheEntry : NSObject {
|
||||
@private
|
||||
id _key;
|
||||
id _object;
|
||||
|
||||
}
|
||||
|
||||
@property (nonatomic, strong, readwrite) id key;
|
||||
@property (nonatomic, strong, readwrite) id object;
|
||||
|
||||
|
||||
-(instancetype) initWithObject:(id)obj forKey:(id)key NS_DESIGNATED_INITIALIZER;
|
||||
|
||||
@end
|
||||
30
Pods/PicoKit/Pod/Core/Cache/PicoCacheEntry.m
generated
Normal file
30
Pods/PicoKit/Pod/Core/Cache/PicoCacheEntry.m
generated
Normal file
@ -0,0 +1,30 @@
|
||||
//
|
||||
// PicoCacheEntry.m
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-25.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#import "PicoCacheEntry.h"
|
||||
|
||||
@implementation PicoCacheEntry
|
||||
|
||||
@synthesize key = _key, object = _object;
|
||||
|
||||
- (instancetype) init {
|
||||
return [self initWithObject:nil forKey:nil];
|
||||
}
|
||||
|
||||
- (instancetype) initWithObject:(id)obj forKey:(id)key {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
self.key = key;
|
||||
self.object = obj;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
@end
|
||||
13
Pods/PicoKit/Pod/Core/Converter/PicoBoolConverter.h
generated
Normal file
13
Pods/PicoKit/Pod/Core/Converter/PicoBoolConverter.h
generated
Normal file
@ -0,0 +1,13 @@
|
||||
//
|
||||
// PicoBoolConverter.h
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-24.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#import "PicoConvertable.h"
|
||||
|
||||
@interface PicoBoolConverter : NSObject <PicoConvertable>
|
||||
|
||||
@end
|
||||
34
Pods/PicoKit/Pod/Core/Converter/PicoBoolConverter.m
generated
Normal file
34
Pods/PicoKit/Pod/Core/Converter/PicoBoolConverter.m
generated
Normal file
@ -0,0 +1,34 @@
|
||||
//
|
||||
// PicoBoolConverter.m
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-24.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#import "PicoBoolConverter.h"
|
||||
|
||||
@implementation PicoBoolConverter
|
||||
|
||||
-(NSString *)write:(NSNumber *)value withConfig:(PicoConfig *)config {
|
||||
if ([value boolValue]) {
|
||||
return @"true";
|
||||
} else {
|
||||
return @"false";
|
||||
}
|
||||
}
|
||||
|
||||
-(NSNumber *)read:(NSString *)value withConfig:(PicoConfig *)config {
|
||||
NSString *lower = [value lowercaseString];
|
||||
NSNumber *result = nil;
|
||||
if ([lower isEqualToString:@"true"]) {
|
||||
result = @YES;
|
||||
} else if ([lower isEqualToString:@"1"]) {
|
||||
result = @YES;
|
||||
} else {
|
||||
result = @NO;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@end
|
||||
16
Pods/PicoKit/Pod/Core/Converter/PicoConvertable.h
generated
Normal file
16
Pods/PicoKit/Pod/Core/Converter/PicoConvertable.h
generated
Normal file
@ -0,0 +1,16 @@
|
||||
//
|
||||
// PicoConvertable.h
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-24.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#import "PicoConfig.h"
|
||||
|
||||
@protocol PicoConvertable <NSObject>
|
||||
|
||||
-(id)read : (NSString *)value withConfig:(PicoConfig *)config;
|
||||
-(NSString *)write: (id)value withConfig:(PicoConfig *)config;
|
||||
|
||||
@end
|
||||
18
Pods/PicoKit/Pod/Core/Converter/PicoConverter.h
generated
Normal file
18
Pods/PicoKit/Pod/Core/Converter/PicoConverter.h
generated
Normal file
@ -0,0 +1,18 @@
|
||||
//
|
||||
// PicoConverter.h
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-24.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#import "PicoConvertable.h"
|
||||
|
||||
@interface PicoConverter : NSObject
|
||||
|
||||
+(id)read: (NSString *)value withType: (NSString *)type config:(PicoConfig *)config;
|
||||
+(NSString *)write: (id)value withType: (NSString *)type config:(PicoConfig *)config;
|
||||
+(BOOL)isPrimitive: (NSString *)type;
|
||||
+(id <PicoConvertable>)lookup: (NSString *)type;
|
||||
|
||||
@end
|
||||
98
Pods/PicoKit/Pod/Core/Converter/PicoConverter.m
generated
Normal file
98
Pods/PicoKit/Pod/Core/Converter/PicoConverter.m
generated
Normal file
@ -0,0 +1,98 @@
|
||||
//
|
||||
// PicoConverter.m
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-24.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#import "PicoConverter.h"
|
||||
#import "PicoConstants.h"
|
||||
#import "PicoNumberConverter.h"
|
||||
#import "PicoBoolConverter.h"
|
||||
#import "PicoStringConverter.h"
|
||||
#import "PicoConvertable.h"
|
||||
#import "PicoDateConverter.h"
|
||||
#import "PicoDataConverter.h"
|
||||
|
||||
@implementation PicoConverter
|
||||
|
||||
static NSMutableDictionary *cache = nil;
|
||||
|
||||
+ (void) initialize {
|
||||
cache = [[NSMutableDictionary alloc] init];
|
||||
|
||||
id <PicoConvertable> converter = nil;
|
||||
|
||||
// pre-initialize converters
|
||||
converter = [[PicoStringConverter alloc] init];
|
||||
cache[PICO_TYPE_STRING] = converter;
|
||||
|
||||
converter = [[PicoNumberConverter alloc] init];
|
||||
cache[PICO_TYPE_INT] = converter;
|
||||
|
||||
converter = [[PicoNumberConverter alloc] init];
|
||||
cache[PICO_TYPE_DOUBLE] = converter;
|
||||
|
||||
converter = [[PicoNumberConverter alloc] init];
|
||||
cache[PICO_TYPE_SHORT] = converter;
|
||||
|
||||
converter = [[PicoNumberConverter alloc] init];
|
||||
cache[PICO_TYPE_LONG] = converter;
|
||||
|
||||
converter = [[PicoNumberConverter alloc] init];
|
||||
cache[PICO_TYPE_FLOAT] = converter;
|
||||
|
||||
converter = [[PicoBoolConverter alloc] init];
|
||||
cache[PICO_TYPE_BOOL] = converter;
|
||||
|
||||
converter = [[PicoStringConverter alloc] init];
|
||||
cache[PICO_TYPE_ENUM] = converter;
|
||||
|
||||
converter = [[PicoDateConverter alloc] init];
|
||||
cache[PICO_TYPE_DATE] = converter;
|
||||
|
||||
converter = [[PicoStringConverter alloc] init];
|
||||
cache[PICO_TYPE_DURATION] = converter;
|
||||
|
||||
converter = [[PicoStringConverter alloc] init];
|
||||
cache[PICO_TYPE_CHAR] = converter;
|
||||
|
||||
converter = [[PicoStringConverter alloc] init];
|
||||
cache[PICO_TYPE_QNAME] = converter;
|
||||
|
||||
converter = [[PicoNumberConverter alloc] init];
|
||||
cache[PICO_TYPE_BYTE] = converter;
|
||||
|
||||
converter = [[PicoDataConverter alloc] init];
|
||||
cache[PICO_TYPE_DATA] = converter;
|
||||
}
|
||||
|
||||
+(id)read: (NSString *)value withType: (NSString *)type config:(PicoConfig *)config {
|
||||
id <PicoConvertable> converter = [PicoConverter lookup:type];
|
||||
if (converter == nil) {
|
||||
@throw [NSException exceptionWithName:@"ConverterException" reason:[NSString stringWithFormat:@"no converter found for type : %@", type] userInfo:nil];
|
||||
}
|
||||
return [converter read:value withConfig:config];
|
||||
}
|
||||
|
||||
+(NSString *)write: (id)value withType: (NSString *)type config:(PicoConfig *)config {
|
||||
id <PicoConvertable> converter = [PicoConverter lookup:type];
|
||||
if (converter == nil) {
|
||||
@throw [NSException exceptionWithName:@"ConverterException" reason:[NSString stringWithFormat:@"no converter found for type : %@", type] userInfo:nil];
|
||||
}
|
||||
return [converter write:value withConfig:config];
|
||||
}
|
||||
|
||||
+(BOOL) isPrimitive:(NSString *)type {
|
||||
return [PicoConverter lookup:type] != nil;
|
||||
}
|
||||
|
||||
+(id <PicoConvertable>)lookup: (NSString *)type {
|
||||
|
||||
id <PicoConvertable> converter = cache[type];
|
||||
return converter;
|
||||
|
||||
}
|
||||
|
||||
@end
|
||||
13
Pods/PicoKit/Pod/Core/Converter/PicoDataConverter.h
generated
Normal file
13
Pods/PicoKit/Pod/Core/Converter/PicoDataConverter.h
generated
Normal file
@ -0,0 +1,13 @@
|
||||
//
|
||||
// PicoDataConverter.h
|
||||
// Pico
|
||||
//
|
||||
// Created by bulldog on 13-3-20.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#include "PicoConvertable.h"
|
||||
|
||||
@interface PicoDataConverter : NSObject<PicoConvertable>
|
||||
|
||||
@end
|
||||
173
Pods/PicoKit/Pod/Core/Converter/PicoDataConverter.m
generated
Normal file
173
Pods/PicoKit/Pod/Core/Converter/PicoDataConverter.m
generated
Normal file
@ -0,0 +1,173 @@
|
||||
//
|
||||
// PicoDataConverter.m
|
||||
// Pico
|
||||
//
|
||||
// Created by bulldog on 13-3-20.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#import "PicoDataConverter.h"
|
||||
|
||||
static const char _base64EncodingTable[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
static const short _base64DecodingTable[256] = {
|
||||
-2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -2, -1, -1, -2, -2,
|
||||
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
|
||||
-1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, -2, -2, 63,
|
||||
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2, -2, -2, -2, -2,
|
||||
-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
|
||||
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -2, -2, -2, -2, -2,
|
||||
-2, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
|
||||
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -2, -2, -2, -2, -2,
|
||||
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
|
||||
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
|
||||
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
|
||||
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
|
||||
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
|
||||
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
|
||||
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
|
||||
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2
|
||||
};
|
||||
|
||||
|
||||
|
||||
@implementation PicoDataConverter
|
||||
|
||||
-(NSString *)write:(NSData *)data withConfig:(PicoConfig *)config {
|
||||
|
||||
NSString *dateString = [PicoDataConverter encodeBase64WithData:data];
|
||||
|
||||
return dateString;
|
||||
}
|
||||
|
||||
-(NSData *)read: (NSString *) value withConfig:(PicoConfig *)config{
|
||||
|
||||
NSData *data = [PicoDataConverter decodeBase64WithString:value];
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
+ (NSString *)encodeBase64WithData:(NSData *)objData {
|
||||
const unsigned char * objRawData = [objData bytes];
|
||||
char * objPointer;
|
||||
char * strResult;
|
||||
|
||||
// Get the Raw Data length and ensure we actually have data
|
||||
int intLength = (int)[objData length];
|
||||
if (intLength == 0) return nil;
|
||||
|
||||
// Setup the String-based Result placeholder and pointer within that placeholder
|
||||
strResult = (char *)calloc((((intLength + 2) / 3) * 4) + 1, sizeof(char));
|
||||
objPointer = strResult;
|
||||
|
||||
// Iterate through everything
|
||||
while (intLength > 2) { // keep going until we have less than 24 bits
|
||||
*objPointer++ = _base64EncodingTable[objRawData[0] >> 2];
|
||||
*objPointer++ = _base64EncodingTable[((objRawData[0] & 0x03) << 4) + (objRawData[1] >> 4)];
|
||||
*objPointer++ = _base64EncodingTable[((objRawData[1] & 0x0f) << 2) + (objRawData[2] >> 6)];
|
||||
*objPointer++ = _base64EncodingTable[objRawData[2] & 0x3f];
|
||||
|
||||
// we just handled 3 octets (24 bits) of data
|
||||
objRawData += 3;
|
||||
intLength -= 3;
|
||||
}
|
||||
|
||||
// now deal with the tail end of things
|
||||
if (intLength != 0) {
|
||||
*objPointer++ = _base64EncodingTable[objRawData[0] >> 2];
|
||||
if (intLength > 1) {
|
||||
*objPointer++ = _base64EncodingTable[((objRawData[0] & 0x03) << 4) + (objRawData[1] >> 4)];
|
||||
*objPointer++ = _base64EncodingTable[(objRawData[1] & 0x0f) << 2];
|
||||
*objPointer++ = '=';
|
||||
} else {
|
||||
*objPointer++ = _base64EncodingTable[(objRawData[0] & 0x03) << 4];
|
||||
*objPointer++ = '=';
|
||||
*objPointer++ = '=';
|
||||
}
|
||||
}
|
||||
|
||||
// Terminate the string-based result
|
||||
*objPointer = '\0';
|
||||
|
||||
// Create result NSString object
|
||||
NSString *base64String = @(strResult);
|
||||
|
||||
// Free memory
|
||||
free(strResult);
|
||||
|
||||
return base64String;
|
||||
}
|
||||
|
||||
+ (NSData *)decodeBase64WithString:(NSString *)strBase64 {
|
||||
const char *objPointer = [strBase64 cStringUsingEncoding:NSASCIIStringEncoding];
|
||||
size_t intLength = strlen(objPointer);
|
||||
int intCurrent;
|
||||
int i = 0, j = 0, k;
|
||||
|
||||
unsigned char *objResult = calloc(intLength, sizeof(unsigned char));
|
||||
|
||||
// Run through the whole string, converting as we go
|
||||
while ( ((intCurrent = *objPointer++) != '\0') && (intLength-- > 0) ) {
|
||||
if (intCurrent == '=') {
|
||||
if (*objPointer != '=' && ((i % 4) == 1)) {// || (intLength > 0)) {
|
||||
// the padding character is invalid at this point -- so this entire string is invalid
|
||||
free(objResult);
|
||||
return nil;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
intCurrent = _base64DecodingTable[intCurrent];
|
||||
if (intCurrent == -1) {
|
||||
// we're at a whitespace -- simply skip over
|
||||
continue;
|
||||
} else if (intCurrent == -2) {
|
||||
// we're at an invalid character
|
||||
free(objResult);
|
||||
return nil;
|
||||
}
|
||||
|
||||
switch (i % 4) {
|
||||
case 0:
|
||||
objResult[j] = intCurrent << 2;
|
||||
break;
|
||||
|
||||
case 1:
|
||||
objResult[j++] |= intCurrent >> 4;
|
||||
objResult[j] = (intCurrent & 0x0f) << 4;
|
||||
break;
|
||||
|
||||
case 2:
|
||||
objResult[j++] |= intCurrent >>2;
|
||||
objResult[j] = (intCurrent & 0x03) << 6;
|
||||
break;
|
||||
|
||||
case 3:
|
||||
objResult[j++] |= intCurrent;
|
||||
break;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
// mop things up if we ended on a boundary
|
||||
k = j;
|
||||
if (intCurrent == '=') {
|
||||
switch (i % 4) {
|
||||
case 1:
|
||||
// Invalid state
|
||||
free(objResult);
|
||||
return nil;
|
||||
|
||||
case 2:
|
||||
k++;
|
||||
// flow through
|
||||
case 3:
|
||||
objResult[k] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup and setup the return NSData
|
||||
NSData * objData = [[NSData alloc] initWithBytes:objResult length:j] ;
|
||||
free(objResult);
|
||||
return objData;
|
||||
}
|
||||
@end
|
||||
13
Pods/PicoKit/Pod/Core/Converter/PicoDateConverter.h
generated
Normal file
13
Pods/PicoKit/Pod/Core/Converter/PicoDateConverter.h
generated
Normal file
@ -0,0 +1,13 @@
|
||||
//
|
||||
// PicoDateConverter.h
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-24.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#include "PicoConvertable.h"
|
||||
|
||||
@interface PicoDateConverter : NSObject <PicoConvertable>
|
||||
|
||||
@end
|
||||
29
Pods/PicoKit/Pod/Core/Converter/PicoDateConverter.m
generated
Normal file
29
Pods/PicoKit/Pod/Core/Converter/PicoDateConverter.m
generated
Normal file
@ -0,0 +1,29 @@
|
||||
//
|
||||
// PicoDateConverter.m
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-24.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#import "PicoDateConverter.h"
|
||||
|
||||
@implementation PicoDateConverter
|
||||
|
||||
-(NSString *)write:(NSDate *)date withConfig:(PicoConfig *)config {
|
||||
|
||||
NSString *dateString = [config.dateFormatter stringFromDate: date];
|
||||
|
||||
return dateString;
|
||||
}
|
||||
|
||||
-(NSDate *)read: (NSString *) value withConfig:(PicoConfig *)config{
|
||||
|
||||
NSDate *date = [config.dateFormatter dateFromString:value];
|
||||
|
||||
return date;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@end
|
||||
13
Pods/PicoKit/Pod/Core/Converter/PicoNumberConverter.h
generated
Normal file
13
Pods/PicoKit/Pod/Core/Converter/PicoNumberConverter.h
generated
Normal file
@ -0,0 +1,13 @@
|
||||
//
|
||||
// PicoNumberConverter.h
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-24.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#include "PicoConvertable.h"
|
||||
|
||||
@interface PicoNumberConverter : NSObject <PicoConvertable>
|
||||
|
||||
@end
|
||||
24
Pods/PicoKit/Pod/Core/Converter/PicoNumberConverter.m
generated
Normal file
24
Pods/PicoKit/Pod/Core/Converter/PicoNumberConverter.m
generated
Normal file
@ -0,0 +1,24 @@
|
||||
//
|
||||
// PicoNumberConverter.m
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-24.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#import "PicoNumberConverter.h"
|
||||
#import "PicoConfig.h"
|
||||
|
||||
@implementation PicoNumberConverter
|
||||
|
||||
-(NSString *)write:(NSNumber *)value withConfig:(PicoConfig *)config {
|
||||
NSString *result = [value stringValue];
|
||||
return result;
|
||||
}
|
||||
|
||||
-(NSNumber *)read:(NSString *)value withConfig:(PicoConfig *)config {
|
||||
NSNumber *result = [config.numberFormatter numberFromString:value];
|
||||
return result;
|
||||
}
|
||||
|
||||
@end
|
||||
13
Pods/PicoKit/Pod/Core/Converter/PicoStringConverter.h
generated
Normal file
13
Pods/PicoKit/Pod/Core/Converter/PicoStringConverter.h
generated
Normal file
@ -0,0 +1,13 @@
|
||||
//
|
||||
// PicoStringConverter.h
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-24.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#include "PicoConvertable.h"
|
||||
|
||||
@interface PicoStringConverter : NSObject <PicoConvertable>
|
||||
|
||||
@end
|
||||
21
Pods/PicoKit/Pod/Core/Converter/PicoStringConverter.m
generated
Normal file
21
Pods/PicoKit/Pod/Core/Converter/PicoStringConverter.m
generated
Normal file
@ -0,0 +1,21 @@
|
||||
//
|
||||
// PicoStringConverter.m
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-24.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#import "PicoStringConverter.h"
|
||||
|
||||
@implementation PicoStringConverter
|
||||
|
||||
-(NSString *)write:(NSString *)value withConfig:(PicoConfig *)config {
|
||||
return value;
|
||||
}
|
||||
|
||||
-(NSString *)read:(NSString *)value withConfig:(PicoConfig *)config {
|
||||
return value;
|
||||
}
|
||||
|
||||
@end
|
||||
15
Pods/PicoKit/Pod/Core/PicoBindable.h
generated
Normal file
15
Pods/PicoKit/Pod/Core/PicoBindable.h
generated
Normal file
@ -0,0 +1,15 @@
|
||||
//
|
||||
// PicoBindable.h
|
||||
// Pico
|
||||
//
|
||||
// Created by bulldog on 13-2-24.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
@class PicoClassSchema;
|
||||
@protocol PicoBindable <NSObject>
|
||||
|
||||
+(PicoClassSchema *)getClassMetaData;
|
||||
+(NSMutableDictionary *)getPropertyMetaData;
|
||||
|
||||
@end
|
||||
47
Pods/PicoKit/Pod/Core/PicoConfig.h
generated
Normal file
47
Pods/PicoKit/Pod/Core/PicoConfig.h
generated
Normal file
@ -0,0 +1,47 @@
|
||||
//
|
||||
// PicoFormat.h
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-26.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
extern NSString *const DEFAULT_XML_ENCODING;
|
||||
|
||||
@interface PicoConfig : NSObject {
|
||||
@private
|
||||
NSString *_encoding;
|
||||
BOOL _indent;
|
||||
NSLocale *_locale;
|
||||
NSNumberFormatter *_numberFormatter;
|
||||
NSDateFormatter *_dateFormatter;
|
||||
NSTimeZone *_tiemZone;
|
||||
}
|
||||
|
||||
/**
|
||||
soap message encoding, default to utf-8
|
||||
*/
|
||||
@property (nonatomic, strong) NSString *encoding;
|
||||
/**
|
||||
locale used for number or date conversion, default to current locale on device
|
||||
*/
|
||||
@property (nonatomic, strong) NSLocale *locale;
|
||||
/**
|
||||
formatter used for number conversion
|
||||
*/
|
||||
@property (nonatomic, strong) NSNumberFormatter *numberFormatter;
|
||||
/**
|
||||
formatter used for date conversion, default date format : yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
|
||||
*/
|
||||
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
|
||||
/**
|
||||
time zone used for date conversion, default to GMT time zone.
|
||||
*/
|
||||
@property (nonatomic, strong) NSTimeZone *timeZone;
|
||||
/**
|
||||
should output message be formated with indent, default to YES
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL indent;
|
||||
|
||||
|
||||
@end
|
||||
38
Pods/PicoKit/Pod/Core/PicoConfig.m
generated
Normal file
38
Pods/PicoKit/Pod/Core/PicoConfig.m
generated
Normal file
@ -0,0 +1,38 @@
|
||||
//
|
||||
// PicoFormat.m
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-26.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#import "PicoConfig.h"
|
||||
|
||||
NSString *const DEFAULT_XML_ENCODING = @"UTF-8";
|
||||
|
||||
@implementation PicoConfig
|
||||
|
||||
@synthesize indent = _indent, encoding = _encoding, locale = _locale, timeZone = _tiemZone;
|
||||
@synthesize numberFormatter = _numberFormatter, dateFormatter = _dateFormatter;
|
||||
|
||||
- (instancetype) init {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
self.indent = YES;
|
||||
self.encoding = DEFAULT_XML_ENCODING;
|
||||
self.locale = [NSLocale currentLocale];
|
||||
_numberFormatter = [[NSNumberFormatter alloc] init];
|
||||
_numberFormatter.locale = self.locale;
|
||||
|
||||
self.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
|
||||
|
||||
_dateFormatter = [[NSDateFormatter alloc] init];
|
||||
[_dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
|
||||
[_dateFormatter setTimeZone:_tiemZone];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
@end
|
||||
95
Pods/PicoKit/Pod/Core/PicoConstants.h
generated
Normal file
95
Pods/PicoKit/Pod/Core/PicoConstants.h
generated
Normal file
@ -0,0 +1,95 @@
|
||||
// binding constants used by PICO framework
|
||||
|
||||
// PICO supported types
|
||||
|
||||
// integer
|
||||
extern NSString *const PICO_TYPE_INT;
|
||||
|
||||
// boolean
|
||||
extern NSString *const PICO_TYPE_BOOL;
|
||||
|
||||
// byte
|
||||
extern NSString *const PICO_TYPE_BYTE;
|
||||
|
||||
// char
|
||||
extern NSString *const PICO_TYPE_CHAR;
|
||||
|
||||
// short
|
||||
extern NSString *const PICO_TYPE_SHORT;
|
||||
|
||||
// long
|
||||
extern NSString *const PICO_TYPE_LONG;
|
||||
|
||||
// float
|
||||
extern NSString *const PICO_TYPE_FLOAT;
|
||||
|
||||
// double
|
||||
extern NSString *const PICO_TYPE_DOUBLE;
|
||||
|
||||
// enum
|
||||
extern NSString *const PICO_TYPE_ENUM;
|
||||
|
||||
// date
|
||||
extern NSString *const PICO_TYPE_DATE;
|
||||
|
||||
// duration
|
||||
extern NSString *const PICO_TYPE_DURATION;
|
||||
|
||||
// object
|
||||
extern NSString *const PICO_TYPE_OBJECT;
|
||||
|
||||
// string
|
||||
extern NSString *const PICO_TYPE_STRING;
|
||||
|
||||
// qname
|
||||
extern NSString *const PICO_TYPE_QNAME;
|
||||
|
||||
// data
|
||||
extern NSString *const PICO_TYPE_DATA;
|
||||
|
||||
// any element
|
||||
extern NSString *const PICO_TYPE_ANYELEMENT;
|
||||
|
||||
// PICO supported property kind
|
||||
|
||||
// map to xml attribute
|
||||
extern NSString *const PICO_KIND_ATTRIBUTE;
|
||||
|
||||
// map to xml element
|
||||
extern NSString *const PICO_KIND_ELEMENT;
|
||||
|
||||
// map to xml element array
|
||||
extern NSString *const PICO_KIND_ELEMENT_ARRAY;
|
||||
|
||||
// map to xml value
|
||||
extern NSString *const PICO_KIND_VALUE;
|
||||
|
||||
// map to xml any element
|
||||
extern NSString *const PICO_KIND_ANY_ELEMENT;
|
||||
|
||||
// meta-data method name
|
||||
|
||||
// method name to get class meta-data
|
||||
extern NSString *const PICO_GET_CLASS_META_DATA_METHOD;
|
||||
|
||||
// method name to get property meta-data
|
||||
extern NSString *const PICO_GET_PROPERTY_META_DATA_METHOD;
|
||||
|
||||
|
||||
// soap version
|
||||
typedef NS_ENUM(NSInteger, PicoSOAPVersion) {
|
||||
SOAP11 = 11,
|
||||
SOAP12 = 12,
|
||||
} ;
|
||||
|
||||
#define PicoErrorDomain @"com.leansoft.pico"
|
||||
|
||||
// pico custom error code
|
||||
typedef NS_ENUM(NSInteger, PicoErrorCode) {
|
||||
ReaderError = -1000,
|
||||
WriterError
|
||||
|
||||
} ;
|
||||
|
||||
|
||||
|
||||
91
Pods/PicoKit/Pod/Core/PicoConstants.m
generated
Normal file
91
Pods/PicoKit/Pod/Core/PicoConstants.m
generated
Normal file
@ -0,0 +1,91 @@
|
||||
//
|
||||
// BindingConstant.m
|
||||
// Pico
|
||||
//
|
||||
// Created by bulldog on 13-2-24.
|
||||
// Copyright (c) 2013 Leansoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#import "PicoConstants.h"
|
||||
|
||||
// binding constants used by PICO framework
|
||||
|
||||
// PICO suppored types
|
||||
|
||||
// integer
|
||||
NSString *const PICO_TYPE_INT = @"int";
|
||||
|
||||
// boolean
|
||||
NSString *const PICO_TYPE_BOOL = @"bool";
|
||||
|
||||
// byte
|
||||
NSString *const PICO_TYPE_BYTE = @"byte";
|
||||
|
||||
// char
|
||||
NSString *const PICO_TYPE_CHAR = @"char";
|
||||
|
||||
// short
|
||||
NSString *const PICO_TYPE_SHORT = @"short";
|
||||
|
||||
// long
|
||||
NSString *const PICO_TYPE_LONG = @"long";
|
||||
|
||||
// float
|
||||
NSString *const PICO_TYPE_FLOAT = @"float";
|
||||
|
||||
// double
|
||||
NSString *const PICO_TYPE_DOUBLE = @"double";
|
||||
|
||||
// enum
|
||||
NSString *const PICO_TYPE_ENUM = @"enum";
|
||||
|
||||
// date
|
||||
NSString *const PICO_TYPE_DATE = @"date";
|
||||
|
||||
// duration
|
||||
NSString *const PICO_TYPE_DURATION = @"duration";
|
||||
|
||||
// object
|
||||
NSString *const PICO_TYPE_OBJECT = @"object";
|
||||
|
||||
// string
|
||||
NSString *const PICO_TYPE_STRING = @"string";
|
||||
|
||||
// qname
|
||||
NSString *const PICO_TYPE_QNAME = @"qname";
|
||||
|
||||
// data
|
||||
NSString *const PICO_TYPE_DATA = @"data";
|
||||
|
||||
// any element
|
||||
NSString *const PICO_TYPE_ANYELEMENT = @"anyElement";
|
||||
|
||||
|
||||
// PICO supported property kind
|
||||
|
||||
// map to xml attribute
|
||||
NSString *const PICO_KIND_ATTRIBUTE = @"Attribute";
|
||||
|
||||
// map to xml element
|
||||
NSString *const PICO_KIND_ELEMENT = @"Element";
|
||||
|
||||
// map to xml element array
|
||||
NSString *const PICO_KIND_ELEMENT_ARRAY = @"ElementArray";
|
||||
|
||||
// map to xml text
|
||||
NSString *const PICO_KIND_VALUE = @"Value";
|
||||
|
||||
// map to xml any element
|
||||
NSString *const PICO_KIND_ANY_ELEMENT = @"AnyElement";
|
||||
|
||||
// meta-data method name
|
||||
|
||||
// method name to get class meta-data
|
||||
NSString *const PICO_GET_CLASS_META_DATA_METHOD = @"getClassMetaData";
|
||||
|
||||
// method name to get property meta-data
|
||||
NSString *const PICO_GET_PROPERTY_META_DATA_METHOD = @"getPropertyMetaData";
|
||||
|
||||
|
||||
|
||||
|
||||
17
Pods/PicoKit/Pod/Core/PicoReadable.h
generated
Normal file
17
Pods/PicoKit/Pod/Core/PicoReadable.h
generated
Normal file
@ -0,0 +1,17 @@
|
||||
//
|
||||
// PicoReadable.h
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-26.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
@protocol PicoReadable <NSObject>
|
||||
|
||||
// Convert binary data to object of specific class
|
||||
-(id)fromData:(NSData *)data withClass:(Class)clazz;
|
||||
|
||||
// Convert string to object of specific class
|
||||
-(id)fromString:(NSString *)string withClass:(Class)clazz;
|
||||
|
||||
@end
|
||||
17
Pods/PicoKit/Pod/Core/PicoWritable.h
generated
Normal file
17
Pods/PicoKit/Pod/Core/PicoWritable.h
generated
Normal file
@ -0,0 +1,17 @@
|
||||
//
|
||||
// PicoWritable.h
|
||||
// pico
|
||||
//
|
||||
// Created by bulldog on 13-2-26.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
@protocol PicoWritable <NSObject>
|
||||
|
||||
// Convert object to binary data
|
||||
-(NSData *)toData:(id)obj;
|
||||
|
||||
// Convert object to string
|
||||
-(NSString *)toString:(id)obj;
|
||||
|
||||
@end
|
||||
24
Pods/PicoKit/Pod/Core/PicoXMLReader.h
generated
Normal file
24
Pods/PicoKit/Pod/Core/PicoXMLReader.h
generated
Normal file
@ -0,0 +1,24 @@
|
||||
//
|
||||
// PicoXMLReader.h
|
||||
// Pico
|
||||
//
|
||||
// Created by bulldog on 13-3-11.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#import "PicoReadable.h"
|
||||
#import "PicoConfig.h"
|
||||
|
||||
@class PicoConfig;
|
||||
@class GDataXMLElement;
|
||||
@interface PicoXMLReader : NSObject <PicoReadable> {
|
||||
@private
|
||||
PicoConfig *_config;
|
||||
|
||||
}
|
||||
|
||||
@property (nonatomic, strong) PicoConfig *config;
|
||||
|
||||
- (instancetype) initWithConfig:(PicoConfig *)config NS_DESIGNATED_INITIALIZER;
|
||||
|
||||
@end
|
||||
280
Pods/PicoKit/Pod/Core/PicoXMLReader.m
generated
Normal file
280
Pods/PicoKit/Pod/Core/PicoXMLReader.m
generated
Normal file
@ -0,0 +1,280 @@
|
||||
//
|
||||
// PicoTBXMLReader.m
|
||||
// Pico
|
||||
//
|
||||
// Created by bulldog on 13-3-11.
|
||||
// Copyright (c) 2013 LeanSoft Technology. All rights reserved.
|
||||
//
|
||||
|
||||
#import "PicoXMLReader.h"
|
||||
#import "GDataXMLNode.h"
|
||||
#import "PicoBindingSchema.h"
|
||||
#import "PicoPropertySchema.h"
|
||||
#import "PicoClassSchema.h"
|
||||
#import "PicoConstants.h"
|
||||
#import "PicoConverter.h"
|
||||
#import "PicoXMLElement.h"
|
||||
|
||||
@implementation PicoXMLReader
|
||||
|
||||
@synthesize config = _config;
|
||||
|
||||
- (instancetype) init {
|
||||
PicoConfig *config = [[PicoConfig alloc] init] ;
|
||||
return [self initWithConfig:config];
|
||||
}
|
||||
|
||||
- (instancetype)initWithConfig:(PicoConfig *)config {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
self.config = config;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
-(id)fromData:(NSData *)data withClass:(Class)clazz {
|
||||
NSError *error;
|
||||
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:data error:&error];
|
||||
|
||||
if (!doc) {
|
||||
@throw [NSException exceptionWithName:@"ReaderException" reason:[NSString stringWithFormat:@"fail to parse xml data , Error : %@", error] userInfo:[error userInfo]];
|
||||
}
|
||||
|
||||
GDataXMLElement *rootElement = [doc rootElement];
|
||||
PicoBindingSchema *bs = [PicoBindingSchema fromClass:clazz];
|
||||
PicoClassSchema *cs = bs.classSchema;
|
||||
NSString *xmlName = cs.xmlName;
|
||||
if ([xmlName length] == 0) {
|
||||
xmlName = bs.className;
|
||||
}
|
||||
NSString *rootName = [rootElement localName];
|
||||
if (![xmlName isEqualToString: rootName]) {
|
||||
@throw [NSException exceptionWithName:@"ReaderException" reason:[NSString stringWithFormat:@"root name mismatch , xml name : %@, root name : %@", xmlName, rootName] userInfo:nil];
|
||||
}
|
||||
|
||||
id obj = [clazz new];
|
||||
|
||||
[self read: obj element: rootElement];
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
-(void)read:(id)value element:(GDataXMLElement *)element {
|
||||
|
||||
[self readAttribute:value element:element];
|
||||
|
||||
|
||||
BOOL hasText = [self readText:value element:element];
|
||||
if (hasText) {
|
||||
return; // no further read if xml text presents
|
||||
}
|
||||
|
||||
[self readElement:value element:element];
|
||||
|
||||
|
||||
[self readAnyElement:value element:element];
|
||||
|
||||
}
|
||||
|
||||
-(void)readAttribute:(id)value element:(GDataXMLElement *)element {
|
||||
PicoBindingSchema *bs = [PicoBindingSchema fromObject:value];
|
||||
|
||||
// read xml attributes
|
||||
NSDictionary *attrMap = bs.xml2AttributeSchemaMapping;
|
||||
if(attrMap.count > 0) {
|
||||
for(NSString *xmlName in attrMap) {
|
||||
PicoPropertySchema *ps = attrMap[xmlName];
|
||||
GDataXMLNode *attrNode = [element attributeForName:xmlName];
|
||||
if (attrNode) {
|
||||
NSString *attrValue = [attrNode stringValue];
|
||||
if ([attrValue length] > 0) {
|
||||
id objValue = [PicoConverter read:attrValue withType:ps.propertyType config:self.config];
|
||||
if (objValue) {
|
||||
[value setValue:objValue forKey: ps.propertyName];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL)readText:(id)value element:(GDataXMLElement *) element {
|
||||
PicoBindingSchema *bs = [PicoBindingSchema fromObject:value];
|
||||
|
||||
// read xml value if any
|
||||
PicoPropertySchema *valuePs = bs.valueSchema;
|
||||
if (valuePs) {
|
||||
NSString *text = [element stringValue];
|
||||
if (text.length > 0) {
|
||||
id objValue = [PicoConverter read: text withType: valuePs.propertyType config:self.config];
|
||||
if (objValue) {
|
||||
[value setValue: objValue forKey: valuePs.propertyName];
|
||||
}
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
-(void)readElement:(id)value element:(GDataXMLElement *)element {
|
||||
PicoBindingSchema *bs = [PicoBindingSchema fromObject:value];
|
||||
|
||||
// read xml element
|
||||
NSDictionary *elementMap = bs.xml2ElementSchemaMapping;
|
||||
NSArray *children = [element children];
|
||||
if (children.count > 0) {
|
||||
for(GDataXMLNode *node in children) {
|
||||
if ([node kind] == GDataXMLElementKind) {
|
||||
GDataXMLElement *childElement = (GDataXMLElement *) node;
|
||||
NSString *localName = childElement.localName;
|
||||
|
||||
PicoPropertySchema *ps = elementMap[localName];
|
||||
|
||||
if (ps) { // found element match
|
||||
|
||||
if ([ps.propertyKind isEqualToString:PICO_KIND_ELEMENT]) {
|
||||
// primitive
|
||||
if ([PicoConverter isPrimitive:ps.propertyType]) {
|
||||
NSString *xmlValue = [childElement stringValue];
|
||||
if (xmlValue.length > 0) {
|
||||
id objValue = [PicoConverter read: xmlValue withType: ps.propertyType config:self.config];
|
||||
if (objValue) {
|
||||
[value setValue: objValue forKey: ps.propertyName];
|
||||
}
|
||||
}
|
||||
} else if ([ps.propertyType isEqualToString:PICO_TYPE_OBJECT]) { // object
|
||||
id obj = [ps.clazz new];
|
||||
[value setValue:obj forKey: ps.propertyName];
|
||||
[self read: obj element: childElement];
|
||||
}
|
||||
} else if ([ps.propertyKind isEqualToString: PICO_KIND_ELEMENT_ARRAY]) {
|
||||
NSMutableArray *array = [value valueForKey:ps.propertyName];
|
||||
if (!array) {
|
||||
array = [[NSMutableArray alloc] init];
|
||||
[value setValue:array forKey: ps.propertyName];
|
||||
}
|
||||
// primitive
|
||||
if ([PicoConverter isPrimitive: ps.propertyType]) {
|
||||
NSString *xmlValue = [childElement stringValue];
|
||||
if (xmlValue.length > 0) {
|
||||
id objValue = [PicoConverter read:xmlValue withType:ps.propertyType config:self.config];
|
||||
[array addObject: objValue];
|
||||
}
|
||||
} else if ([ps.propertyType isEqualToString:PICO_TYPE_OBJECT]) { // object
|
||||
id obj = [ps.clazz new];
|
||||
[array addObject:obj];
|
||||
[self read: obj element: childElement];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-(void)readAnyElement:(id)value element:(GDataXMLElement *)element {
|
||||
PicoBindingSchema *bs = [PicoBindingSchema fromObject:value];
|
||||
|
||||
// read xml any element
|
||||
PicoPropertySchema *anyPs = bs.anyElementSchema;
|
||||
if (anyPs) {
|
||||
if (anyPs.clazz) { // target class specified
|
||||
[self readAnyElement:value element:element bindClass:anyPs.clazz];
|
||||
} else {
|
||||
NSMutableArray *anyChildElements = [[NSMutableArray alloc] init];
|
||||
NSArray *children = [element children];
|
||||
|
||||
NSDictionary *elementMap = bs.xml2ElementSchemaMapping;
|
||||
|
||||
for(GDataXMLNode *node in children) {
|
||||
if ([node kind] == GDataXMLElementKind) {
|
||||
if (elementMap.count == 0 || !elementMap[[node localName]]) {
|
||||
PicoXMLElement *picoElement = [self convertToPicoElement:(GDataXMLElement *)node];
|
||||
[anyChildElements addObject:picoElement];
|
||||
}
|
||||
}
|
||||
}
|
||||
[value setValue:anyChildElements forKey: anyPs.propertyName];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL)readAnyElement:(id)value element:(GDataXMLElement *)element bindClass:(Class) clazz {
|
||||
BOOL result = NO;
|
||||
PicoBindingSchema *bs = [PicoBindingSchema fromClass:clazz];
|
||||
PicoClassSchema *cs = [bs classSchema];;
|
||||
NSString *xmlName = cs.xmlName;
|
||||
if ([xmlName length] == 0) {
|
||||
xmlName = bs.className;
|
||||
}
|
||||
NSMutableArray *childElements = [[NSMutableArray alloc] init];
|
||||
NSArray *children = [element children];
|
||||
for(GDataXMLNode *node in children) {
|
||||
if ([node kind] == GDataXMLElementKind && [xmlName isEqualToString:[node localName]]) {
|
||||
[childElements addObject:node];
|
||||
}
|
||||
}
|
||||
if (childElements.count > 0) {
|
||||
|
||||
PicoBindingSchema *bs = [PicoBindingSchema fromObject:value];
|
||||
|
||||
// read xml any element
|
||||
PicoPropertySchema *anyPs = bs.anyElementSchema;
|
||||
|
||||
NSMutableArray *array = [[NSMutableArray alloc] init];
|
||||
[value setValue:array forKey: anyPs.propertyName];
|
||||
for(GDataXMLElement *childElement in childElements) {
|
||||
id obj = [clazz new];
|
||||
[array addObject:obj];
|
||||
[self read: obj element: childElement];
|
||||
}
|
||||
result = YES;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
-(PicoXMLElement *)convertToPicoElement:(GDataXMLElement *)element {
|
||||
PicoXMLElement *picoElement = [[PicoXMLElement alloc] init] ;
|
||||
picoElement.name = element.localName;
|
||||
picoElement.nsUri = element.URI;
|
||||
if ([element childCount] == 1) {
|
||||
GDataXMLNode *node = (element.children)[0];
|
||||
if (node.kind == GDataXMLTextKind) {
|
||||
picoElement.value = node.stringValue;
|
||||
}
|
||||
}
|
||||
if (element.attributes) {
|
||||
NSMutableDictionary *attrDic = [[NSMutableDictionary alloc] init];
|
||||
picoElement.attributes = attrDic;
|
||||
for(GDataXMLNode *attr in element.attributes) {
|
||||
attrDic[attr.localName] = attr.stringValue;
|
||||
}
|
||||
}
|
||||
if (element.children) {
|
||||
NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
|
||||
picoElement.children = childrenArray;
|
||||
for(GDataXMLNode *node in element.children) {
|
||||
if ([node kind] == GDataXMLElementKind) {
|
||||
PicoXMLElement *childPicoElement = [self convertToPicoElement:(GDataXMLElement *)node];
|
||||
childPicoElement.parent = picoElement;
|
||||
[childrenArray addObject: childPicoElement];
|
||||
}
|
||||
}
|
||||
}
|
||||
return picoElement;
|
||||
}
|
||||
|
||||
|
||||
-(id)fromString:(NSString *)string withClass:(Class)clazz {
|
||||
NSData *data = [string dataUsingEncoding: CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)self.config.encoding)) allowLossyConversion:NO];
|
||||
|
||||
return [self fromData:data withClass:clazz];
|
||||
}
|
||||
|
||||
|
||||
|
||||
@end
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user