forked from loafle/openapi-generator-original
Fix problem with multitheard api client
This commit is contained in:
parent
a893168291
commit
e40f9abdbb
@ -246,9 +246,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
|||||||
supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h"));
|
supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h"));
|
||||||
supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m"));
|
supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m"));
|
||||||
supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h"));
|
supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h"));
|
||||||
supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m"));
|
supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m"));
|
||||||
supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m"));
|
supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m"));
|
||||||
supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h"));
|
supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h"));
|
||||||
supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m"));
|
supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m"));
|
||||||
|
@ -1,21 +1,13 @@
|
|||||||
#import <ISO8601/NSDate+ISO8601.h>
|
|
||||||
|
|
||||||
#import "{{classPrefix}}Logger.h"
|
#import "{{classPrefix}}Logger.h"
|
||||||
#import "{{classPrefix}}ApiClient.h"
|
#import "{{classPrefix}}ApiClient.h"
|
||||||
#import "{{classPrefix}}JSONRequestSerializer.h"
|
#import "{{classPrefix}}JSONRequestSerializer.h"
|
||||||
#import "{{classPrefix}}JSONResponseSerializer.h"
|
|
||||||
#import "{{classPrefix}}QueryParamCollection.h"
|
#import "{{classPrefix}}QueryParamCollection.h"
|
||||||
#import "{{classPrefix}}DefaultConfiguration.h"
|
#import "{{classPrefix}}DefaultConfiguration.h"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject";
|
NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject";
|
||||||
|
|
||||||
static bool offlineState = false;
|
static NSString * const k{{classPrefix}}ContentDispositionKey = @"Content-Disposition";
|
||||||
static bool cacheEnabled = false;
|
|
||||||
static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable;
|
|
||||||
static void (^reachabilityChangeBlock)(int);
|
|
||||||
|
|
||||||
|
|
||||||
static NSDictionary * {{classPrefix}}__headerFieldsForResponse(NSURLResponse *response) {
|
static NSDictionary * {{classPrefix}}__headerFieldsForResponse(NSURLResponse *response) {
|
||||||
if(![response isKindOfClass:[NSHTTPURLResponse class]]) {
|
if(![response isKindOfClass:[NSHTTPURLResponse class]]) {
|
||||||
@ -26,17 +18,13 @@ static NSDictionary * {{classPrefix}}__headerFieldsForResponse(NSURLResponse *re
|
|||||||
|
|
||||||
static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) {
|
static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) {
|
||||||
NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response);
|
NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response);
|
||||||
if(!headers[@"Content-Disposition"]) {
|
if(!headers[k{{classPrefix}}ContentDispositionKey]) {
|
||||||
return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
|
return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
|
||||||
}
|
}
|
||||||
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?";
|
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?";
|
||||||
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern
|
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
|
||||||
options:NSRegularExpressionCaseInsensitive
|
NSString *contentDispositionHeader = headers[k{{classPrefix}}ContentDispositionKey];
|
||||||
error:nil];
|
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader options:0 range:NSMakeRange(0, [contentDispositionHeader length])];
|
||||||
NSString *contentDispositionHeader = headers[@"Content-Disposition"];
|
|
||||||
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader
|
|
||||||
options:0
|
|
||||||
range:NSMakeRange(0, [contentDispositionHeader length])];
|
|
||||||
return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]];
|
return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -45,6 +33,8 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
|
|||||||
|
|
||||||
@property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration;
|
@property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration;
|
||||||
|
|
||||||
|
@property (nonatomic, strong) NSArray<NSString*>* downloadTaskResponseTypes;
|
||||||
|
|
||||||
@end
|
@end
|
||||||
|
|
||||||
@implementation {{classPrefix}}ApiClient
|
@implementation {{classPrefix}}ApiClient
|
||||||
@ -75,7 +65,6 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
|
|||||||
}
|
}
|
||||||
|
|
||||||
- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<{{classPrefix}}Configuration>)configuration {
|
- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<{{classPrefix}}Configuration>)configuration {
|
||||||
|
|
||||||
self = [super initWithBaseURL:url];
|
self = [super initWithBaseURL:url];
|
||||||
if (self) {
|
if (self) {
|
||||||
_configuration = configuration;
|
_configuration = configuration;
|
||||||
@ -83,102 +72,30 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
|
|||||||
_responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init];
|
_responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init];
|
||||||
_sanitizer = [[{{classPrefix}}Sanitizer alloc] init];
|
_sanitizer = [[{{classPrefix}}Sanitizer alloc] init];
|
||||||
|
|
||||||
self.requestSerializer = [AFJSONRequestSerializer serializer];
|
_downloadTaskResponseTypes = @[@"NSURL*", @"NSURL"];
|
||||||
self.responseSerializer = [AFJSONResponseSerializer serializer];
|
|
||||||
self.securityPolicy = [self customSecurityPolicy];
|
|
||||||
|
|
||||||
// configure reachability
|
AFHTTPRequestSerializer* afhttpRequestSerializer = [AFHTTPRequestSerializer serializer];
|
||||||
[self configureCacheReachibility];
|
SWGJSONRequestSerializer * swgjsonRequestSerializer = [SWGJSONRequestSerializer serializer];
|
||||||
|
_requestSerializerForContentType = @{kSWGApplicationJSONType : swgjsonRequestSerializer,
|
||||||
|
@"application/x-www-form-urlencoded": afhttpRequestSerializer,
|
||||||
|
@"multipart/form-data": afhttpRequestSerializer
|
||||||
|
};
|
||||||
|
self.securityPolicy = [self createSecurityPolicy];
|
||||||
|
self.responseSerializer = [AFHTTPResponseSerializer serializer];
|
||||||
}
|
}
|
||||||
|
|
||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
#pragma mark - Setter Methods
|
|
||||||
|
|
||||||
+ (void) setOfflineState:(BOOL) state {
|
|
||||||
offlineState = state;
|
|
||||||
}
|
|
||||||
|
|
||||||
+ (void) setCacheEnabled:(BOOL)enabled {
|
|
||||||
cacheEnabled = enabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status {
|
|
||||||
reachabilityStatus = status;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey {
|
|
||||||
[self.requestSerializer setValue:value forHTTPHeaderField:forKey];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)setRequestSerializer:(AFHTTPRequestSerializer<AFURLRequestSerialization> *)requestSerializer {
|
|
||||||
[super setRequestSerializer:requestSerializer];
|
|
||||||
requestSerializer.timeoutInterval = self.timeoutInterval;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Cache Methods
|
|
||||||
|
|
||||||
+(void)clearCache {
|
|
||||||
[[NSURLCache sharedURLCache] removeAllCachedResponses];
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize
|
|
||||||
diskSize: (unsigned long) diskSize {
|
|
||||||
NSAssert(memorySize > 0, @"invalid in-memory cache size");
|
|
||||||
NSAssert(diskSize >= 0, @"invalid disk cache size");
|
|
||||||
|
|
||||||
NSURLCache *cache =
|
|
||||||
[[NSURLCache alloc]
|
|
||||||
initWithMemoryCapacity:memorySize
|
|
||||||
diskCapacity:diskSize
|
|
||||||
diskPath:@"swagger_url_cache"];
|
|
||||||
|
|
||||||
[NSURLCache setSharedURLCache:cache];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Reachability Methods
|
|
||||||
|
|
||||||
+(AFNetworkReachabilityStatus) getReachabilityStatus {
|
|
||||||
return reachabilityStatus;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(BOOL) getOfflineState {
|
|
||||||
return offlineState;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock {
|
|
||||||
reachabilityChangeBlock = changeBlock;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) configureCacheReachibility {
|
|
||||||
[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
|
|
||||||
reachabilityStatus = status;
|
|
||||||
{{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status));
|
|
||||||
[{{classPrefix}}ApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable];
|
|
||||||
|
|
||||||
// call the reachability block, if configured
|
|
||||||
if (reachabilityChangeBlock != nil) {
|
|
||||||
reachabilityChangeBlock(status);
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
|
|
||||||
[self.reachabilityManager startMonitoring];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Task Methods
|
#pragma mark - Task Methods
|
||||||
|
|
||||||
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request
|
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock {
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
|
||||||
|
|
||||||
NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
|
NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
|
||||||
{{classPrefix}}DebugLogResponse(response, responseObject,request,error);
|
{{classPrefix}}DebugLogResponse(response, responseObject,request,error);
|
||||||
|
|
||||||
if(!error) {
|
if(!error) {
|
||||||
completionBlock(responseObject, nil);
|
completionBlock(responseObject, nil);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
|
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
|
||||||
if (responseObject) {
|
if (responseObject) {
|
||||||
// Add in the (parsed) response body.
|
// Add in the (parsed) response body.
|
||||||
@ -191,10 +108,9 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
|
|||||||
return task;
|
return task;
|
||||||
}
|
}
|
||||||
|
|
||||||
- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request
|
- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock {
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
|
||||||
|
__block NSString * tempFolderPath = [self.configuration.tempFolderPath copy];
|
||||||
id<{{classPrefix}}Configuration> config = self.configuration;
|
|
||||||
|
|
||||||
NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
|
NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
|
||||||
{{classPrefix}}DebugLogResponse(response, responseObject,request,error);
|
{{classPrefix}}DebugLogResponse(response, responseObject,request,error);
|
||||||
@ -206,9 +122,10 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
|
|||||||
}
|
}
|
||||||
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
|
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
|
||||||
completionBlock(nil, augmentedError);
|
completionBlock(nil, augmentedError);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory();
|
NSString *directory = tempFolderPath ?: NSTemporaryDirectory();
|
||||||
NSString *filename = {{classPrefix}}__fileNameForResponse(response);
|
NSString *filename = {{classPrefix}}__fileNameForResponse(response);
|
||||||
|
|
||||||
NSString *filepath = [directory stringByAppendingPathComponent:filename];
|
NSString *filepath = [directory stringByAppendingPathComponent:filename];
|
||||||
@ -238,35 +155,17 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
|
|||||||
responseType: (NSString *) responseType
|
responseType: (NSString *) responseType
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
completionBlock: (void (^)(id, NSError *))completionBlock {
|
||||||
|
|
||||||
// setting request serializer
|
AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer = [self requestSerializerForRequestContentType:requestContentType];
|
||||||
if ([requestContentType isEqualToString:@"application/json"]) {
|
|
||||||
self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else if ([requestContentType isEqualToString:@"multipart/form-data"]) {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
NSAssert(NO, @"Unsupported request type %@", requestContentType);
|
|
||||||
}
|
|
||||||
|
|
||||||
// setting response serializer
|
__weak id<SWGSanitizer> sanitizer = self.sanitizer;
|
||||||
if ([responseContentType isEqualToString:@"application/json"]) {
|
|
||||||
self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer];
|
|
||||||
} else {
|
|
||||||
self.responseSerializer = [AFHTTPResponseSerializer serializer];
|
|
||||||
}
|
|
||||||
|
|
||||||
// sanitize parameters
|
// sanitize parameters
|
||||||
pathParams = [self.sanitizer sanitizeForSerialization:pathParams];
|
pathParams = [sanitizer sanitizeForSerialization:pathParams];
|
||||||
queryParams = [self.sanitizer sanitizeForSerialization:queryParams];
|
queryParams = [sanitizer sanitizeForSerialization:queryParams];
|
||||||
headerParams = [self.sanitizer sanitizeForSerialization:headerParams];
|
headerParams = [sanitizer sanitizeForSerialization:headerParams];
|
||||||
formParams = [self.sanitizer sanitizeForSerialization:formParams];
|
formParams = [sanitizer sanitizeForSerialization:formParams];
|
||||||
if(![body isKindOfClass:[NSData class]]) {
|
if(![body isKindOfClass:[NSData class]]) {
|
||||||
body = [self.sanitizer sanitizeForSerialization:body];
|
body = [sanitizer sanitizeForSerialization:body];
|
||||||
}
|
}
|
||||||
|
|
||||||
// auth setting
|
// auth setting
|
||||||
@ -279,22 +178,19 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
|
|||||||
[resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString];
|
[resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString];
|
||||||
}];
|
}];
|
||||||
|
|
||||||
NSMutableURLRequest * request = nil;
|
|
||||||
|
|
||||||
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams];
|
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams];
|
||||||
if ([pathWithQueryParams hasPrefix:@"/"]) {
|
if ([pathWithQueryParams hasPrefix:@"/"]) {
|
||||||
pathWithQueryParams = [pathWithQueryParams substringFromIndex:1];
|
pathWithQueryParams = [pathWithQueryParams substringFromIndex:1];
|
||||||
}
|
}
|
||||||
|
|
||||||
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
|
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
|
||||||
|
|
||||||
|
NSError *requestCreateError = nil;
|
||||||
|
NSMutableURLRequest * request = nil;
|
||||||
if (files.count > 0) {
|
if (files.count > 0) {
|
||||||
__weak __typeof(self)weakSelf = self;
|
request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
|
||||||
request = [self.requestSerializer multipartFormRequestWithMethod:@"POST"
|
|
||||||
URLString:urlString
|
|
||||||
parameters:nil
|
|
||||||
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
|
|
||||||
[formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
[formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
||||||
NSString *objString = [weakSelf.sanitizer parameterToString:obj];
|
NSString *objString = [sanitizer parameterToString:obj];
|
||||||
NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding];
|
NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding];
|
||||||
[formData appendPartWithFormData:data name:key];
|
[formData appendPartWithFormData:data name:key];
|
||||||
}];
|
}];
|
||||||
@ -302,59 +198,43 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
|
|||||||
NSURL *filePath = (NSURL *)obj;
|
NSURL *filePath = (NSURL *)obj;
|
||||||
[formData appendPartWithFileURL:filePath name:key error:nil];
|
[formData appendPartWithFileURL:filePath name:key error:nil];
|
||||||
}];
|
}];
|
||||||
} error:nil];
|
} error:&requestCreateError];
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
if (formParams) {
|
if (formParams) {
|
||||||
request = [self.requestSerializer requestWithMethod:method
|
request = [requestSerializer requestWithMethod:method URLString:urlString parameters:formParams error:&requestCreateError];
|
||||||
URLString:urlString
|
|
||||||
parameters:formParams
|
|
||||||
error:nil];
|
|
||||||
}
|
}
|
||||||
if (body) {
|
if (body) {
|
||||||
request = [self.requestSerializer requestWithMethod:method
|
request = [requestSerializer requestWithMethod:method URLString:urlString parameters:body error:&requestCreateError];
|
||||||
URLString:urlString
|
|
||||||
parameters:body
|
|
||||||
error:nil];
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if(!request) {
|
||||||
// request cache
|
completionBlock(nil, requestCreateError);
|
||||||
BOOL hasHeaderParams = [headerParams count] > 0;
|
return nil;
|
||||||
if (offlineState) {
|
|
||||||
{{classPrefix}}DebugLog(@"%@ cache forced", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
|
|
||||||
}
|
|
||||||
else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) {
|
|
||||||
{{classPrefix}}DebugLog(@"%@ cache enabled", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
{{classPrefix}}DebugLog(@"%@ cache disabled", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hasHeaderParams){
|
if ([headerParams count] > 0){
|
||||||
for(NSString * key in [headerParams keyEnumerator]){
|
for(NSString * key in [headerParams keyEnumerator]){
|
||||||
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
|
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
[self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
|
[requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
|
||||||
|
|
||||||
[self postProcessRequest:request];
|
[self postProcessRequest:request];
|
||||||
|
|
||||||
|
|
||||||
NSURLSessionTask *task = nil;
|
NSURLSessionTask *task = nil;
|
||||||
|
|
||||||
if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) {
|
if ([self.downloadTaskResponseTypes containsObject:responseType]) {
|
||||||
task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
||||||
completionBlock(data, error);
|
completionBlock(data, error);
|
||||||
}];
|
}];
|
||||||
}
|
} else {
|
||||||
else {
|
__weak typeof(self) weakSelf = self;
|
||||||
task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
||||||
NSError * serializationError;
|
NSError * serializationError;
|
||||||
id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError];
|
id response = [weakSelf.responseDeserializer deserialize:data class:responseType error:&serializationError];
|
||||||
|
|
||||||
if(!response && !error){
|
if(!response && !error){
|
||||||
error = serializationError;
|
error = serializationError;
|
||||||
}
|
}
|
||||||
@ -367,16 +247,24 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
|
|||||||
return task;
|
return task;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
-(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializerForRequestContentType:(NSString *)requestContentType {
|
||||||
|
AFHTTPRequestSerializer <AFURLRequestSerialization> * serializer = self.requestSerializerForContentType[requestContentType];
|
||||||
|
if(!serializer) {
|
||||||
|
NSAssert(NO, @"Unsupported request content type %@", requestContentType);
|
||||||
|
serializer = [AFHTTPRequestSerializer serializer];
|
||||||
|
}
|
||||||
|
serializer.timeoutInterval = self.timeoutInterval;
|
||||||
|
return serializer;
|
||||||
|
}
|
||||||
|
|
||||||
//Added for easier override to modify request
|
//Added for easier override to modify request
|
||||||
-(void)postProcessRequest:(NSMutableURLRequest *)request {
|
-(void)postProcessRequest:(NSMutableURLRequest *)request {
|
||||||
// Always disable cookies!
|
|
||||||
[request setHTTPShouldHandleCookies:NO];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#pragma mark -
|
#pragma mark -
|
||||||
|
|
||||||
- (NSString*) pathWithQueryParamsToString:(NSString*) path
|
- (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams {
|
||||||
queryParams:(NSDictionary*) queryParams {
|
|
||||||
if(queryParams.count == 0) {
|
if(queryParams.count == 0) {
|
||||||
return path;
|
return path;
|
||||||
}
|
}
|
||||||
@ -434,9 +322,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
|
|||||||
/**
|
/**
|
||||||
* Update header and query params based on authentication settings
|
* Update header and query params based on authentication settings
|
||||||
*/
|
*/
|
||||||
- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers
|
- (void) updateHeaderParams:(NSDictionary * *)headers queryParams:(NSDictionary * *)querys WithAuthSettings:(NSArray *)authSettings {
|
||||||
queryParams:(NSDictionary *__autoreleasing *)querys
|
|
||||||
WithAuthSettings:(NSArray *)authSettings {
|
|
||||||
|
|
||||||
if ([authSettings count] == 0) {
|
if ([authSettings count] == 0) {
|
||||||
return;
|
return;
|
||||||
@ -466,7 +352,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
|
|||||||
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
|
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
|
||||||
}
|
}
|
||||||
|
|
||||||
- (AFSecurityPolicy *) customSecurityPolicy {
|
- (AFSecurityPolicy *) createSecurityPolicy {
|
||||||
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
|
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
|
||||||
|
|
||||||
id<{{classPrefix}}Configuration> config = self.configuration;
|
id<{{classPrefix}}Configuration> config = self.configuration;
|
||||||
|
@ -17,78 +17,19 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
|
|||||||
|
|
||||||
@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration;
|
@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration;
|
||||||
|
|
||||||
@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
|
|
||||||
@property(nonatomic, assign) NSTimeInterval timeoutInterval;
|
@property(nonatomic, assign) NSTimeInterval timeoutInterval;
|
||||||
@property(nonatomic, readonly) NSOperationQueue* queue;
|
|
||||||
|
|
||||||
@property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer;
|
@property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer;
|
||||||
|
|
||||||
@property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer;
|
@property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer;
|
||||||
/**
|
|
||||||
* Clears Cache
|
|
||||||
*/
|
|
||||||
+(void)clearCache;
|
|
||||||
|
|
||||||
/**
|
@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer <AFURLRequestSerialization> *>* requestSerializerForContentType;
|
||||||
* Turns on cache
|
|
||||||
*
|
|
||||||
* @param enabled If the cached is enable, must be `YES` or `NO`
|
|
||||||
*/
|
|
||||||
+(void)setCacheEnabled:(BOOL) enabled;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the client unreachable
|
|
||||||
*
|
|
||||||
* @param state off line state, must be `YES` or `NO`
|
|
||||||
*/
|
|
||||||
+(void) setOfflineState:(BOOL) state;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets if the client is unreachable
|
|
||||||
*
|
|
||||||
* @return The client offline state
|
|
||||||
*/
|
|
||||||
+(BOOL) getOfflineState;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the client reachability, this may be overridden by the reachability manager if reachability changes
|
|
||||||
*
|
|
||||||
* @param The client reachability.
|
|
||||||
*/
|
|
||||||
+(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the client reachability
|
|
||||||
*
|
|
||||||
* @return The client reachability.
|
|
||||||
*/
|
|
||||||
+(AFNetworkReachabilityStatus) getReachabilityStatus;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Customizes the behavior when the reachability changed
|
|
||||||
*
|
|
||||||
* @param changeBlock The block will be executed when the reachability changed.
|
|
||||||
*/
|
|
||||||
+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets client singleton instance
|
* Gets client singleton instance
|
||||||
*/
|
*/
|
||||||
+ (instancetype) sharedClient;
|
+ (instancetype) sharedClient;
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the api client reachability strategy
|
|
||||||
*/
|
|
||||||
- (void)configureCacheReachibility;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets header for request
|
|
||||||
*
|
|
||||||
* @param value The header value
|
|
||||||
* @param forKey The header key
|
|
||||||
*/
|
|
||||||
-(void)setHeaderValue:(NSString*) value
|
|
||||||
forKey:(NSString*) forKey;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Updates header parameters and query parameters for authentication
|
* Updates header parameters and query parameters for authentication
|
||||||
@ -97,9 +38,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
|
|||||||
* @param querys The query parameters will be updated, passed by pointer to pointer.
|
* @param querys The query parameters will be updated, passed by pointer to pointer.
|
||||||
* @param authSettings The authentication names NSArray.
|
* @param authSettings The authentication names NSArray.
|
||||||
*/
|
*/
|
||||||
- (void) updateHeaderParams:(NSDictionary **)headers
|
- (void) updateHeaderParams:(NSDictionary **)headers queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings;
|
||||||
queryParams:(NSDictionary **)querys
|
|
||||||
WithAuthSettings:(NSArray *)authSettings;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -109,6 +48,14 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
|
|||||||
*/
|
*/
|
||||||
- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration;
|
- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initializes the session manager with a configuration and url
|
||||||
|
*
|
||||||
|
* @param url The base url
|
||||||
|
* @param configuration The configuration implementation
|
||||||
|
*/
|
||||||
|
- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<SWGConfiguration>)configuration;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Performs request
|
* Performs request
|
||||||
*
|
*
|
||||||
@ -139,11 +86,4 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
|
|||||||
responseType: (NSString *) responseType
|
responseType: (NSString *) responseType
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock;
|
completionBlock: (void (^)(id, NSError *))completionBlock;
|
||||||
|
|
||||||
/**
|
|
||||||
* Custom security policy
|
|
||||||
*
|
|
||||||
* @return AFSecurityPolicy
|
|
||||||
*/
|
|
||||||
- (AFSecurityPolicy *) customSecurityPolicy;
|
|
||||||
|
|
||||||
@end
|
@end
|
||||||
|
@ -36,7 +36,7 @@
|
|||||||
_mutableApiKey = [NSMutableDictionary dictionary];
|
_mutableApiKey = [NSMutableDictionary dictionary];
|
||||||
_mutableApiKeyPrefix = [NSMutableDictionary dictionary];
|
_mutableApiKeyPrefix = [NSMutableDictionary dictionary];
|
||||||
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
|
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
|
||||||
{{#httpUserAgent}}_mutableDefaultHeaders[@"User-Agent"] = @"{{httpUserAgent}}"{{/httpUserAgent}};
|
{{#httpUserAgent}}_mutableDefaultHeaders[@"User-Agent"] = @"{{httpUserAgent}}";{{/httpUserAgent}}
|
||||||
_logger = [{{classPrefix}}Logger sharedLogger];
|
_logger = [{{classPrefix}}Logger sharedLogger];
|
||||||
}
|
}
|
||||||
return self;
|
return self;
|
||||||
@ -144,8 +144,6 @@
|
|||||||
self.logger.enabled = debug;
|
self.logger.enabled = debug;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key {
|
- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key {
|
||||||
if(!value) {
|
if(!value) {
|
||||||
[self.mutableDefaultHeaders removeObjectForKey:key];
|
[self.mutableDefaultHeaders removeObjectForKey:key];
|
||||||
|
@ -1,39 +0,0 @@
|
|||||||
#import "{{classPrefix}}JSONResponseSerializer.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}JSONResponseSerializer
|
|
||||||
|
|
||||||
///
|
|
||||||
/// When customize a response serializer,
|
|
||||||
/// the serializer must conform the protocol `AFURLResponseSerialization`
|
|
||||||
/// and implements the protocol method `responseObjectForResponse:error:`
|
|
||||||
///
|
|
||||||
/// @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.
|
|
||||||
///
|
|
||||||
- (id) responseObjectForResponse:(NSURLResponse *)response
|
|
||||||
data:(NSData *)data
|
|
||||||
error:(NSError *__autoreleasing *)error {
|
|
||||||
NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error];
|
|
||||||
|
|
||||||
// if response data is not a valid json, return string of data.
|
|
||||||
if ([self isParseError:*error]) {
|
|
||||||
*error = nil;
|
|
||||||
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
|
||||||
return responseString;
|
|
||||||
}
|
|
||||||
|
|
||||||
return responseJson;
|
|
||||||
}
|
|
||||||
|
|
||||||
-(BOOL)isParseError:(NSError *)error {
|
|
||||||
return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840;
|
|
||||||
}
|
|
||||||
|
|
||||||
+ (instancetype)serializer {
|
|
||||||
return [self serializerWithReadingOptions:NSJSONReadingAllowFragments];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,8 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <AFNetworking/AFURLResponseSerialization.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}JSONResponseSerializer : AFJSONResponseSerializer
|
|
||||||
|
|
||||||
@end
|
|
@ -17,8 +17,7 @@
|
|||||||
|
|
||||||
#pragma mark - Log Methods
|
#pragma mark - Log Methods
|
||||||
|
|
||||||
- (void)debugLog:(NSString *)method
|
- (void)debugLog:(NSString *)method message:(NSString *)format, ... {
|
||||||
message:(NSString *)format, ... {
|
|
||||||
if (!self.isEnabled) {
|
if (!self.isEnabled) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -16,6 +16,7 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528;
|
|||||||
@property (nonatomic, strong) NSNumberFormatter* numberFormatter;
|
@property (nonatomic, strong) NSNumberFormatter* numberFormatter;
|
||||||
@property (nonatomic, strong) NSArray *primitiveTypes;
|
@property (nonatomic, strong) NSArray *primitiveTypes;
|
||||||
@property (nonatomic, strong) NSArray *basicReturnTypes;
|
@property (nonatomic, strong) NSArray *basicReturnTypes;
|
||||||
|
@property (nonatomic, strong) NSArray *dataReturnTypes;
|
||||||
|
|
||||||
@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression;
|
@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression;
|
||||||
@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression;
|
@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression;
|
||||||
@ -33,7 +34,9 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528;
|
|||||||
formatter.numberStyle = NSNumberFormatterDecimalStyle;
|
formatter.numberStyle = NSNumberFormatterDecimalStyle;
|
||||||
_numberFormatter = formatter;
|
_numberFormatter = formatter;
|
||||||
_primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"];
|
_primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"];
|
||||||
_basicReturnTypes = @[@"NSObject", @"id", @"NSData"];
|
_basicReturnTypes = @[@"NSObject", @"id"];
|
||||||
|
_dataReturnTypes = @[@"NSData"];
|
||||||
|
|
||||||
_arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>"
|
_arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>"
|
||||||
options:NSRegularExpressionCaseInsensitive
|
options:NSRegularExpressionCaseInsensitive
|
||||||
error:nil];
|
error:nil];
|
||||||
@ -53,23 +56,36 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528;
|
|||||||
#pragma mark - Deserialize methods
|
#pragma mark - Deserialize methods
|
||||||
|
|
||||||
- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error {
|
- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error {
|
||||||
// return nil if data is nil or className is nil
|
if (!data || !className) {
|
||||||
if (!data || !className || [data isKindOfClass:[NSNull class]]) {
|
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove "*" from className, if ends with "*"
|
|
||||||
if ([className hasSuffix:@"*"]) {
|
if ([className hasSuffix:@"*"]) {
|
||||||
className = [className substringToIndex:[className length] - 1];
|
className = [className substringToIndex:[className length] - 1];
|
||||||
}
|
}
|
||||||
|
if([self.dataReturnTypes containsObject:className]) {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
id jsonData = nil;
|
||||||
|
if([data isKindOfClass:[NSData class]]) {
|
||||||
|
jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:error];
|
||||||
|
} else {
|
||||||
|
jsonData = data;
|
||||||
|
}
|
||||||
|
if(!jsonData) {
|
||||||
|
jsonData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
||||||
|
} else if([jsonData isKindOfClass:[NSNull class]]) {
|
||||||
|
return nil;
|
||||||
|
}
|
||||||
|
|
||||||
// pure object
|
// pure object
|
||||||
if ([self.basicReturnTypes containsObject:className]) {
|
if ([self.basicReturnTypes containsObject:className]) {
|
||||||
return data;
|
return jsonData;
|
||||||
}
|
}
|
||||||
|
|
||||||
// primitives
|
// primitives
|
||||||
if ([self.primitiveTypes containsObject:className]) {
|
if ([self.primitiveTypes containsObject:className]) {
|
||||||
return [self deserializePrimitiveValue:data class:className error:error];
|
return [self deserializePrimitiveValue:jsonData class:className error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
NSTextCheckingResult *match = nil;
|
NSTextCheckingResult *match = nil;
|
||||||
@ -78,37 +94,37 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528;
|
|||||||
match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range];
|
match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range];
|
||||||
if (match) {
|
if (match) {
|
||||||
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
|
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
|
||||||
return [self deserializeArrayValue:data innerType:innerType error:error];
|
return [self deserializeArrayValue:jsonData innerType:innerType error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
// list of primitives
|
// list of primitives
|
||||||
match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range];
|
match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range];
|
||||||
if (match) {
|
if (match) {
|
||||||
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
|
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
|
||||||
return [self deserializeArrayValue:data innerType:innerType error:error];
|
return [self deserializeArrayValue:jsonData innerType:innerType error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
// map
|
// map
|
||||||
match = [self.dictPatExpression firstMatchInString:className options:0 range:range];
|
match = [self.dictPatExpression firstMatchInString:className options:0 range:range];
|
||||||
if (match) {
|
if (match) {
|
||||||
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
|
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
|
||||||
return [self deserializeDictionaryValue:data valueType:valueType error:error];
|
return [self deserializeDictionaryValue:jsonData valueType:valueType error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range];
|
match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range];
|
||||||
if (match) {
|
if (match) {
|
||||||
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
|
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
|
||||||
return [self deserializeDictionaryValue:data valueType:valueType error:error];
|
return [self deserializeDictionaryValue:jsonData valueType:valueType error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
// model
|
// model
|
||||||
Class ModelClass = NSClassFromString(className);
|
Class ModelClass = NSClassFromString(className);
|
||||||
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
|
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
|
||||||
return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error];
|
return [(JSONModel *) [ModelClass alloc] initWithDictionary:jsonData error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
if(error) {
|
if(error) {
|
||||||
*error = [self unknownResponseErrorWithExpectedType:className data:data];
|
*error = [self unknownResponseErrorWithExpectedType:className data:jsonData];
|
||||||
}
|
}
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
@ -172,7 +188,7 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528;
|
|||||||
|
|
||||||
- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error {
|
- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error {
|
||||||
if ([className isEqualToString:@"NSString"]) {
|
if ([className isEqualToString:@"NSString"]) {
|
||||||
return [NSString stringWithString:data];
|
return [NSString stringWithFormat:@"%@",data];
|
||||||
}
|
}
|
||||||
else if ([className isEqualToString:@"NSDate"]) {
|
else if ([className isEqualToString:@"NSDate"]) {
|
||||||
return [self deserializeDateValue:data error:error];
|
return [self deserializeDateValue:data error:error];
|
||||||
|
@ -3,6 +3,8 @@
|
|||||||
#import "{{classPrefix}}QueryParamCollection.h"
|
#import "{{classPrefix}}QueryParamCollection.h"
|
||||||
#import <ISO8601/ISO8601.h>
|
#import <ISO8601/ISO8601.h>
|
||||||
|
|
||||||
|
NSString * const k{{classPrefix}}ApplicationJSONType = @"application/json";
|
||||||
|
|
||||||
NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) {
|
NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) {
|
||||||
static NSString * const k{{classPrefix}}CharactersGeneralDelimitersToEncode = @":#[]@";
|
static NSString * const k{{classPrefix}}CharactersGeneralDelimitersToEncode = @":#[]@";
|
||||||
static NSString * const k{{classPrefix}}CharactersSubDelimitersToEncode = @"!$&'()*+,;=";
|
static NSString * const k{{classPrefix}}CharactersSubDelimitersToEncode = @"!$&'()*+,;=";
|
||||||
@ -43,8 +45,6 @@ NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) {
|
|||||||
|
|
||||||
@implementation {{classPrefix}}Sanitizer
|
@implementation {{classPrefix}}Sanitizer
|
||||||
|
|
||||||
static NSString * kApplicationJSONType = @"application/json";
|
|
||||||
|
|
||||||
-(instancetype)init {
|
-(instancetype)init {
|
||||||
self = [super init];
|
self = [super init];
|
||||||
if ( !self ) {
|
if ( !self ) {
|
||||||
@ -141,7 +141,7 @@ static NSString * kApplicationJSONType = @"application/json";
|
|||||||
NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]];
|
NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]];
|
||||||
for (NSString *string in accepts) {
|
for (NSString *string in accepts) {
|
||||||
if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) {
|
if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) {
|
||||||
return kApplicationJSONType;
|
return k{{classPrefix}}ApplicationJSONType;
|
||||||
}
|
}
|
||||||
[lowerAccepts addObject:[string lowercaseString]];
|
[lowerAccepts addObject:[string lowercaseString]];
|
||||||
}
|
}
|
||||||
@ -153,12 +153,12 @@ static NSString * kApplicationJSONType = @"application/json";
|
|||||||
*/
|
*/
|
||||||
- (NSString *) selectHeaderContentType:(NSArray *)contentTypes {
|
- (NSString *) selectHeaderContentType:(NSArray *)contentTypes {
|
||||||
if (contentTypes.count == 0) {
|
if (contentTypes.count == 0) {
|
||||||
return kApplicationJSONType;
|
return k{{classPrefix}}ApplicationJSONType;
|
||||||
}
|
}
|
||||||
NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]];
|
NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]];
|
||||||
for (NSString *string in contentTypes) {
|
for (NSString *string in contentTypes) {
|
||||||
if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){
|
if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){
|
||||||
return kApplicationJSONType;
|
return k{{classPrefix}}ApplicationJSONType;
|
||||||
}
|
}
|
||||||
[lowerContentTypes addObject:[string lowercaseString]];
|
[lowerContentTypes addObject:[string lowercaseString]];
|
||||||
}
|
}
|
||||||
|
@ -4,6 +4,8 @@
|
|||||||
|
|
||||||
extern NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string);
|
extern NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string);
|
||||||
|
|
||||||
|
extern NSString * const k{{classPrefix}}ApplicationJSONType;
|
||||||
|
|
||||||
@protocol {{classPrefix}}Sanitizer <NSObject>
|
@protocol {{classPrefix}}Sanitizer <NSObject>
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi
|
|||||||
|
|
||||||
- API version: 1.0.0
|
- API version: 1.0.0
|
||||||
- Package version:
|
- Package version:
|
||||||
- Build date: 2016-08-17T10:06:58.453+02:00
|
- Build date: 2016-08-23T10:56:27.632+02:00
|
||||||
- Build package: class io.swagger.codegen.languages.ObjcClientCodegen
|
- Build package: class io.swagger.codegen.languages.ObjcClientCodegen
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
@ -39,78 +39,19 @@ extern NSString *const SWGResponseObjectErrorKey;
|
|||||||
|
|
||||||
@property (nonatomic, strong, readonly) id<SWGConfiguration> configuration;
|
@property (nonatomic, strong, readonly) id<SWGConfiguration> configuration;
|
||||||
|
|
||||||
@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
|
|
||||||
@property(nonatomic, assign) NSTimeInterval timeoutInterval;
|
@property(nonatomic, assign) NSTimeInterval timeoutInterval;
|
||||||
@property(nonatomic, readonly) NSOperationQueue* queue;
|
|
||||||
|
|
||||||
@property(nonatomic, strong) id<SWGResponseDeserializer> responseDeserializer;
|
@property(nonatomic, strong) id<SWGResponseDeserializer> responseDeserializer;
|
||||||
|
|
||||||
@property(nonatomic, strong) id<SWGSanitizer> sanitizer;
|
@property(nonatomic, strong) id<SWGSanitizer> sanitizer;
|
||||||
/**
|
|
||||||
* Clears Cache
|
|
||||||
*/
|
|
||||||
+(void)clearCache;
|
|
||||||
|
|
||||||
/**
|
@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer <AFURLRequestSerialization> *>* requestSerializerForContentType;
|
||||||
* Turns on cache
|
|
||||||
*
|
|
||||||
* @param enabled If the cached is enable, must be `YES` or `NO`
|
|
||||||
*/
|
|
||||||
+(void)setCacheEnabled:(BOOL) enabled;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the client unreachable
|
|
||||||
*
|
|
||||||
* @param state off line state, must be `YES` or `NO`
|
|
||||||
*/
|
|
||||||
+(void) setOfflineState:(BOOL) state;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets if the client is unreachable
|
|
||||||
*
|
|
||||||
* @return The client offline state
|
|
||||||
*/
|
|
||||||
+(BOOL) getOfflineState;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the client reachability, this may be overridden by the reachability manager if reachability changes
|
|
||||||
*
|
|
||||||
* @param The client reachability.
|
|
||||||
*/
|
|
||||||
+(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the client reachability
|
|
||||||
*
|
|
||||||
* @return The client reachability.
|
|
||||||
*/
|
|
||||||
+(AFNetworkReachabilityStatus) getReachabilityStatus;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Customizes the behavior when the reachability changed
|
|
||||||
*
|
|
||||||
* @param changeBlock The block will be executed when the reachability changed.
|
|
||||||
*/
|
|
||||||
+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets client singleton instance
|
* Gets client singleton instance
|
||||||
*/
|
*/
|
||||||
+ (instancetype) sharedClient;
|
+ (instancetype) sharedClient;
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the api client reachability strategy
|
|
||||||
*/
|
|
||||||
- (void)configureCacheReachibility;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets header for request
|
|
||||||
*
|
|
||||||
* @param value The header value
|
|
||||||
* @param forKey The header key
|
|
||||||
*/
|
|
||||||
-(void)setHeaderValue:(NSString*) value
|
|
||||||
forKey:(NSString*) forKey;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Updates header parameters and query parameters for authentication
|
* Updates header parameters and query parameters for authentication
|
||||||
@ -119,9 +60,7 @@ extern NSString *const SWGResponseObjectErrorKey;
|
|||||||
* @param querys The query parameters will be updated, passed by pointer to pointer.
|
* @param querys The query parameters will be updated, passed by pointer to pointer.
|
||||||
* @param authSettings The authentication names NSArray.
|
* @param authSettings The authentication names NSArray.
|
||||||
*/
|
*/
|
||||||
- (void) updateHeaderParams:(NSDictionary **)headers
|
- (void) updateHeaderParams:(NSDictionary **)headers queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings;
|
||||||
queryParams:(NSDictionary **)querys
|
|
||||||
WithAuthSettings:(NSArray *)authSettings;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -131,6 +70,14 @@ extern NSString *const SWGResponseObjectErrorKey;
|
|||||||
*/
|
*/
|
||||||
- (instancetype)initWithConfiguration:(id<SWGConfiguration>)configuration;
|
- (instancetype)initWithConfiguration:(id<SWGConfiguration>)configuration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initializes the session manager with a configuration and url
|
||||||
|
*
|
||||||
|
* @param url The base url
|
||||||
|
* @param configuration The configuration implementation
|
||||||
|
*/
|
||||||
|
- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<SWGConfiguration>)configuration;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Performs request
|
* Performs request
|
||||||
*
|
*
|
||||||
@ -161,11 +108,4 @@ extern NSString *const SWGResponseObjectErrorKey;
|
|||||||
responseType: (NSString *) responseType
|
responseType: (NSString *) responseType
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock;
|
completionBlock: (void (^)(id, NSError *))completionBlock;
|
||||||
|
|
||||||
/**
|
|
||||||
* Custom security policy
|
|
||||||
*
|
|
||||||
* @return AFSecurityPolicy
|
|
||||||
*/
|
|
||||||
- (AFSecurityPolicy *) customSecurityPolicy;
|
|
||||||
|
|
||||||
@end
|
@end
|
||||||
|
@ -1,21 +1,13 @@
|
|||||||
#import <ISO8601/NSDate+ISO8601.h>
|
|
||||||
|
|
||||||
#import "SWGLogger.h"
|
#import "SWGLogger.h"
|
||||||
#import "SWGApiClient.h"
|
#import "SWGApiClient.h"
|
||||||
#import "SWGJSONRequestSerializer.h"
|
#import "SWGJSONRequestSerializer.h"
|
||||||
#import "SWGJSONResponseSerializer.h"
|
|
||||||
#import "SWGQueryParamCollection.h"
|
#import "SWGQueryParamCollection.h"
|
||||||
#import "SWGDefaultConfiguration.h"
|
#import "SWGDefaultConfiguration.h"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject";
|
NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject";
|
||||||
|
|
||||||
static bool offlineState = false;
|
static NSString * const kSWGContentDispositionKey = @"Content-Disposition";
|
||||||
static bool cacheEnabled = false;
|
|
||||||
static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable;
|
|
||||||
static void (^reachabilityChangeBlock)(int);
|
|
||||||
|
|
||||||
|
|
||||||
static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) {
|
static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) {
|
||||||
if(![response isKindOfClass:[NSHTTPURLResponse class]]) {
|
if(![response isKindOfClass:[NSHTTPURLResponse class]]) {
|
||||||
@ -26,17 +18,13 @@ static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) {
|
|||||||
|
|
||||||
static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
||||||
NSDictionary * headers = SWG__headerFieldsForResponse(response);
|
NSDictionary * headers = SWG__headerFieldsForResponse(response);
|
||||||
if(!headers[@"Content-Disposition"]) {
|
if(!headers[kSWGContentDispositionKey]) {
|
||||||
return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
|
return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
|
||||||
}
|
}
|
||||||
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?";
|
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?";
|
||||||
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern
|
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
|
||||||
options:NSRegularExpressionCaseInsensitive
|
NSString *contentDispositionHeader = headers[kSWGContentDispositionKey];
|
||||||
error:nil];
|
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader options:0 range:NSMakeRange(0, [contentDispositionHeader length])];
|
||||||
NSString *contentDispositionHeader = headers[@"Content-Disposition"];
|
|
||||||
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader
|
|
||||||
options:0
|
|
||||||
range:NSMakeRange(0, [contentDispositionHeader length])];
|
|
||||||
return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]];
|
return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -45,6 +33,8 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
|
|
||||||
@property (nonatomic, strong, readwrite) id<SWGConfiguration> configuration;
|
@property (nonatomic, strong, readwrite) id<SWGConfiguration> configuration;
|
||||||
|
|
||||||
|
@property (nonatomic, strong) NSArray<NSString*>* downloadTaskResponseTypes;
|
||||||
|
|
||||||
@end
|
@end
|
||||||
|
|
||||||
@implementation SWGApiClient
|
@implementation SWGApiClient
|
||||||
@ -75,7 +65,6 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<SWGConfiguration>)configuration {
|
- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<SWGConfiguration>)configuration {
|
||||||
|
|
||||||
self = [super initWithBaseURL:url];
|
self = [super initWithBaseURL:url];
|
||||||
if (self) {
|
if (self) {
|
||||||
_configuration = configuration;
|
_configuration = configuration;
|
||||||
@ -83,102 +72,30 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
_responseDeserializer = [[SWGResponseDeserializer alloc] init];
|
_responseDeserializer = [[SWGResponseDeserializer alloc] init];
|
||||||
_sanitizer = [[SWGSanitizer alloc] init];
|
_sanitizer = [[SWGSanitizer alloc] init];
|
||||||
|
|
||||||
self.requestSerializer = [AFJSONRequestSerializer serializer];
|
_downloadTaskResponseTypes = @[@"NSURL*", @"NSURL"];
|
||||||
self.responseSerializer = [AFJSONResponseSerializer serializer];
|
|
||||||
self.securityPolicy = [self customSecurityPolicy];
|
|
||||||
|
|
||||||
// configure reachability
|
AFHTTPRequestSerializer* afhttpRequestSerializer = [AFHTTPRequestSerializer serializer];
|
||||||
[self configureCacheReachibility];
|
SWGJSONRequestSerializer * swgjsonRequestSerializer = [SWGJSONRequestSerializer serializer];
|
||||||
|
_requestSerializerForContentType = @{kSWGApplicationJSONType : swgjsonRequestSerializer,
|
||||||
|
@"application/x-www-form-urlencoded": afhttpRequestSerializer,
|
||||||
|
@"multipart/form-data": afhttpRequestSerializer
|
||||||
|
};
|
||||||
|
self.securityPolicy = [self createSecurityPolicy];
|
||||||
|
self.responseSerializer = [AFHTTPResponseSerializer serializer];
|
||||||
}
|
}
|
||||||
|
|
||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
#pragma mark - Setter Methods
|
|
||||||
|
|
||||||
+ (void) setOfflineState:(BOOL) state {
|
|
||||||
offlineState = state;
|
|
||||||
}
|
|
||||||
|
|
||||||
+ (void) setCacheEnabled:(BOOL)enabled {
|
|
||||||
cacheEnabled = enabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status {
|
|
||||||
reachabilityStatus = status;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey {
|
|
||||||
[self.requestSerializer setValue:value forHTTPHeaderField:forKey];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)setRequestSerializer:(AFHTTPRequestSerializer<AFURLRequestSerialization> *)requestSerializer {
|
|
||||||
[super setRequestSerializer:requestSerializer];
|
|
||||||
requestSerializer.timeoutInterval = self.timeoutInterval;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Cache Methods
|
|
||||||
|
|
||||||
+(void)clearCache {
|
|
||||||
[[NSURLCache sharedURLCache] removeAllCachedResponses];
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize
|
|
||||||
diskSize: (unsigned long) diskSize {
|
|
||||||
NSAssert(memorySize > 0, @"invalid in-memory cache size");
|
|
||||||
NSAssert(diskSize >= 0, @"invalid disk cache size");
|
|
||||||
|
|
||||||
NSURLCache *cache =
|
|
||||||
[[NSURLCache alloc]
|
|
||||||
initWithMemoryCapacity:memorySize
|
|
||||||
diskCapacity:diskSize
|
|
||||||
diskPath:@"swagger_url_cache"];
|
|
||||||
|
|
||||||
[NSURLCache setSharedURLCache:cache];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Reachability Methods
|
|
||||||
|
|
||||||
+(AFNetworkReachabilityStatus) getReachabilityStatus {
|
|
||||||
return reachabilityStatus;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(BOOL) getOfflineState {
|
|
||||||
return offlineState;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock {
|
|
||||||
reachabilityChangeBlock = changeBlock;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) configureCacheReachibility {
|
|
||||||
[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
|
|
||||||
reachabilityStatus = status;
|
|
||||||
SWGDebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status));
|
|
||||||
[SWGApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable];
|
|
||||||
|
|
||||||
// call the reachability block, if configured
|
|
||||||
if (reachabilityChangeBlock != nil) {
|
|
||||||
reachabilityChangeBlock(status);
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
|
|
||||||
[self.reachabilityManager startMonitoring];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Task Methods
|
#pragma mark - Task Methods
|
||||||
|
|
||||||
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request
|
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock {
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
|
||||||
|
|
||||||
NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
|
NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
|
||||||
SWGDebugLogResponse(response, responseObject,request,error);
|
SWGDebugLogResponse(response, responseObject,request,error);
|
||||||
|
|
||||||
if(!error) {
|
if(!error) {
|
||||||
completionBlock(responseObject, nil);
|
completionBlock(responseObject, nil);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
|
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
|
||||||
if (responseObject) {
|
if (responseObject) {
|
||||||
// Add in the (parsed) response body.
|
// Add in the (parsed) response body.
|
||||||
@ -191,10 +108,9 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
return task;
|
return task;
|
||||||
}
|
}
|
||||||
|
|
||||||
- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request
|
- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock {
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
|
||||||
|
__block NSString * tempFolderPath = [self.configuration.tempFolderPath copy];
|
||||||
id<SWGConfiguration> config = self.configuration;
|
|
||||||
|
|
||||||
NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
|
NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
|
||||||
SWGDebugLogResponse(response, responseObject,request,error);
|
SWGDebugLogResponse(response, responseObject,request,error);
|
||||||
@ -206,9 +122,10 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
}
|
}
|
||||||
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
|
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
|
||||||
completionBlock(nil, augmentedError);
|
completionBlock(nil, augmentedError);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory();
|
NSString *directory = tempFolderPath ?: NSTemporaryDirectory();
|
||||||
NSString *filename = SWG__fileNameForResponse(response);
|
NSString *filename = SWG__fileNameForResponse(response);
|
||||||
|
|
||||||
NSString *filepath = [directory stringByAppendingPathComponent:filename];
|
NSString *filepath = [directory stringByAppendingPathComponent:filename];
|
||||||
@ -238,35 +155,17 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
responseType: (NSString *) responseType
|
responseType: (NSString *) responseType
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
completionBlock: (void (^)(id, NSError *))completionBlock {
|
||||||
|
|
||||||
// setting request serializer
|
AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer = [self requestSerializerForRequestContentType:requestContentType];
|
||||||
if ([requestContentType isEqualToString:@"application/json"]) {
|
|
||||||
self.requestSerializer = [SWGJSONRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else if ([requestContentType isEqualToString:@"multipart/form-data"]) {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
NSAssert(NO, @"Unsupported request type %@", requestContentType);
|
|
||||||
}
|
|
||||||
|
|
||||||
// setting response serializer
|
__weak id<SWGSanitizer> sanitizer = self.sanitizer;
|
||||||
if ([responseContentType isEqualToString:@"application/json"]) {
|
|
||||||
self.responseSerializer = [SWGJSONResponseSerializer serializer];
|
|
||||||
} else {
|
|
||||||
self.responseSerializer = [AFHTTPResponseSerializer serializer];
|
|
||||||
}
|
|
||||||
|
|
||||||
// sanitize parameters
|
// sanitize parameters
|
||||||
pathParams = [self.sanitizer sanitizeForSerialization:pathParams];
|
pathParams = [sanitizer sanitizeForSerialization:pathParams];
|
||||||
queryParams = [self.sanitizer sanitizeForSerialization:queryParams];
|
queryParams = [sanitizer sanitizeForSerialization:queryParams];
|
||||||
headerParams = [self.sanitizer sanitizeForSerialization:headerParams];
|
headerParams = [sanitizer sanitizeForSerialization:headerParams];
|
||||||
formParams = [self.sanitizer sanitizeForSerialization:formParams];
|
formParams = [sanitizer sanitizeForSerialization:formParams];
|
||||||
if(![body isKindOfClass:[NSData class]]) {
|
if(![body isKindOfClass:[NSData class]]) {
|
||||||
body = [self.sanitizer sanitizeForSerialization:body];
|
body = [sanitizer sanitizeForSerialization:body];
|
||||||
}
|
}
|
||||||
|
|
||||||
// auth setting
|
// auth setting
|
||||||
@ -279,22 +178,19 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
[resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString];
|
[resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString];
|
||||||
}];
|
}];
|
||||||
|
|
||||||
NSMutableURLRequest * request = nil;
|
|
||||||
|
|
||||||
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams];
|
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams];
|
||||||
if ([pathWithQueryParams hasPrefix:@"/"]) {
|
if ([pathWithQueryParams hasPrefix:@"/"]) {
|
||||||
pathWithQueryParams = [pathWithQueryParams substringFromIndex:1];
|
pathWithQueryParams = [pathWithQueryParams substringFromIndex:1];
|
||||||
}
|
}
|
||||||
|
|
||||||
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
|
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
|
||||||
|
|
||||||
|
NSError *requestCreateError = nil;
|
||||||
|
NSMutableURLRequest * request = nil;
|
||||||
if (files.count > 0) {
|
if (files.count > 0) {
|
||||||
__weak __typeof(self)weakSelf = self;
|
request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
|
||||||
request = [self.requestSerializer multipartFormRequestWithMethod:@"POST"
|
|
||||||
URLString:urlString
|
|
||||||
parameters:nil
|
|
||||||
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
|
|
||||||
[formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
[formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
||||||
NSString *objString = [weakSelf.sanitizer parameterToString:obj];
|
NSString *objString = [sanitizer parameterToString:obj];
|
||||||
NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding];
|
NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding];
|
||||||
[formData appendPartWithFormData:data name:key];
|
[formData appendPartWithFormData:data name:key];
|
||||||
}];
|
}];
|
||||||
@ -302,59 +198,43 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
NSURL *filePath = (NSURL *)obj;
|
NSURL *filePath = (NSURL *)obj;
|
||||||
[formData appendPartWithFileURL:filePath name:key error:nil];
|
[formData appendPartWithFileURL:filePath name:key error:nil];
|
||||||
}];
|
}];
|
||||||
} error:nil];
|
} error:&requestCreateError];
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
if (formParams) {
|
if (formParams) {
|
||||||
request = [self.requestSerializer requestWithMethod:method
|
request = [requestSerializer requestWithMethod:method URLString:urlString parameters:formParams error:&requestCreateError];
|
||||||
URLString:urlString
|
|
||||||
parameters:formParams
|
|
||||||
error:nil];
|
|
||||||
}
|
}
|
||||||
if (body) {
|
if (body) {
|
||||||
request = [self.requestSerializer requestWithMethod:method
|
request = [requestSerializer requestWithMethod:method URLString:urlString parameters:body error:&requestCreateError];
|
||||||
URLString:urlString
|
|
||||||
parameters:body
|
|
||||||
error:nil];
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if(!request) {
|
||||||
// request cache
|
completionBlock(nil, requestCreateError);
|
||||||
BOOL hasHeaderParams = [headerParams count] > 0;
|
return nil;
|
||||||
if (offlineState) {
|
|
||||||
SWGDebugLog(@"%@ cache forced", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
|
|
||||||
}
|
|
||||||
else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) {
|
|
||||||
SWGDebugLog(@"%@ cache enabled", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
SWGDebugLog(@"%@ cache disabled", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hasHeaderParams){
|
if ([headerParams count] > 0){
|
||||||
for(NSString * key in [headerParams keyEnumerator]){
|
for(NSString * key in [headerParams keyEnumerator]){
|
||||||
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
|
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
[self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
|
[requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
|
||||||
|
|
||||||
[self postProcessRequest:request];
|
[self postProcessRequest:request];
|
||||||
|
|
||||||
|
|
||||||
NSURLSessionTask *task = nil;
|
NSURLSessionTask *task = nil;
|
||||||
|
|
||||||
if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) {
|
if ([self.downloadTaskResponseTypes containsObject:responseType]) {
|
||||||
task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
||||||
completionBlock(data, error);
|
completionBlock(data, error);
|
||||||
}];
|
}];
|
||||||
}
|
} else {
|
||||||
else {
|
__weak typeof(self) weakSelf = self;
|
||||||
task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
||||||
NSError * serializationError;
|
NSError * serializationError;
|
||||||
id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError];
|
id response = [weakSelf.responseDeserializer deserialize:data class:responseType error:&serializationError];
|
||||||
|
|
||||||
if(!response && !error){
|
if(!response && !error){
|
||||||
error = serializationError;
|
error = serializationError;
|
||||||
}
|
}
|
||||||
@ -367,16 +247,24 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
return task;
|
return task;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
-(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializerForRequestContentType:(NSString *)requestContentType {
|
||||||
|
AFHTTPRequestSerializer <AFURLRequestSerialization> * serializer = self.requestSerializerForContentType[requestContentType];
|
||||||
|
if(!serializer) {
|
||||||
|
NSAssert(NO, @"Unsupported request content type %@", requestContentType);
|
||||||
|
serializer = [AFHTTPRequestSerializer serializer];
|
||||||
|
}
|
||||||
|
serializer.timeoutInterval = self.timeoutInterval;
|
||||||
|
return serializer;
|
||||||
|
}
|
||||||
|
|
||||||
//Added for easier override to modify request
|
//Added for easier override to modify request
|
||||||
-(void)postProcessRequest:(NSMutableURLRequest *)request {
|
-(void)postProcessRequest:(NSMutableURLRequest *)request {
|
||||||
// Always disable cookies!
|
|
||||||
[request setHTTPShouldHandleCookies:NO];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#pragma mark -
|
#pragma mark -
|
||||||
|
|
||||||
- (NSString*) pathWithQueryParamsToString:(NSString*) path
|
- (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams {
|
||||||
queryParams:(NSDictionary*) queryParams {
|
|
||||||
if(queryParams.count == 0) {
|
if(queryParams.count == 0) {
|
||||||
return path;
|
return path;
|
||||||
}
|
}
|
||||||
@ -434,9 +322,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
/**
|
/**
|
||||||
* Update header and query params based on authentication settings
|
* Update header and query params based on authentication settings
|
||||||
*/
|
*/
|
||||||
- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers
|
- (void) updateHeaderParams:(NSDictionary * *)headers queryParams:(NSDictionary * *)querys WithAuthSettings:(NSArray *)authSettings {
|
||||||
queryParams:(NSDictionary *__autoreleasing *)querys
|
|
||||||
WithAuthSettings:(NSArray *)authSettings {
|
|
||||||
|
|
||||||
if ([authSettings count] == 0) {
|
if ([authSettings count] == 0) {
|
||||||
return;
|
return;
|
||||||
@ -466,7 +352,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
|
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
|
||||||
}
|
}
|
||||||
|
|
||||||
- (AFSecurityPolicy *) customSecurityPolicy {
|
- (AFSecurityPolicy *) createSecurityPolicy {
|
||||||
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
|
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
|
||||||
|
|
||||||
id<SWGConfiguration> config = self.configuration;
|
id<SWGConfiguration> config = self.configuration;
|
||||||
|
@ -36,7 +36,7 @@
|
|||||||
_mutableApiKey = [NSMutableDictionary dictionary];
|
_mutableApiKey = [NSMutableDictionary dictionary];
|
||||||
_mutableApiKeyPrefix = [NSMutableDictionary dictionary];
|
_mutableApiKeyPrefix = [NSMutableDictionary dictionary];
|
||||||
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
|
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
|
||||||
;
|
|
||||||
_logger = [SWGLogger sharedLogger];
|
_logger = [SWGLogger sharedLogger];
|
||||||
}
|
}
|
||||||
return self;
|
return self;
|
||||||
@ -129,8 +129,6 @@
|
|||||||
self.logger.enabled = debug;
|
self.logger.enabled = debug;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key {
|
- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key {
|
||||||
if(!value) {
|
if(!value) {
|
||||||
[self.mutableDefaultHeaders removeObjectForKey:key];
|
[self.mutableDefaultHeaders removeObjectForKey:key];
|
||||||
|
@ -17,8 +17,7 @@
|
|||||||
|
|
||||||
#pragma mark - Log Methods
|
#pragma mark - Log Methods
|
||||||
|
|
||||||
- (void)debugLog:(NSString *)method
|
- (void)debugLog:(NSString *)method message:(NSString *)format, ... {
|
||||||
message:(NSString *)format, ... {
|
|
||||||
if (!self.isEnabled) {
|
if (!self.isEnabled) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -16,6 +16,7 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
|
|||||||
@property (nonatomic, strong) NSNumberFormatter* numberFormatter;
|
@property (nonatomic, strong) NSNumberFormatter* numberFormatter;
|
||||||
@property (nonatomic, strong) NSArray *primitiveTypes;
|
@property (nonatomic, strong) NSArray *primitiveTypes;
|
||||||
@property (nonatomic, strong) NSArray *basicReturnTypes;
|
@property (nonatomic, strong) NSArray *basicReturnTypes;
|
||||||
|
@property (nonatomic, strong) NSArray *dataReturnTypes;
|
||||||
|
|
||||||
@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression;
|
@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression;
|
||||||
@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression;
|
@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression;
|
||||||
@ -33,7 +34,9 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
|
|||||||
formatter.numberStyle = NSNumberFormatterDecimalStyle;
|
formatter.numberStyle = NSNumberFormatterDecimalStyle;
|
||||||
_numberFormatter = formatter;
|
_numberFormatter = formatter;
|
||||||
_primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"];
|
_primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"];
|
||||||
_basicReturnTypes = @[@"NSObject", @"id", @"NSData"];
|
_basicReturnTypes = @[@"NSObject", @"id"];
|
||||||
|
_dataReturnTypes = @[@"NSData"];
|
||||||
|
|
||||||
_arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>"
|
_arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>"
|
||||||
options:NSRegularExpressionCaseInsensitive
|
options:NSRegularExpressionCaseInsensitive
|
||||||
error:nil];
|
error:nil];
|
||||||
@ -53,23 +56,36 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
|
|||||||
#pragma mark - Deserialize methods
|
#pragma mark - Deserialize methods
|
||||||
|
|
||||||
- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error {
|
- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error {
|
||||||
// return nil if data is nil or className is nil
|
if (!data || !className) {
|
||||||
if (!data || !className || [data isKindOfClass:[NSNull class]]) {
|
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove "*" from className, if ends with "*"
|
|
||||||
if ([className hasSuffix:@"*"]) {
|
if ([className hasSuffix:@"*"]) {
|
||||||
className = [className substringToIndex:[className length] - 1];
|
className = [className substringToIndex:[className length] - 1];
|
||||||
}
|
}
|
||||||
|
if([self.dataReturnTypes containsObject:className]) {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
id jsonData = nil;
|
||||||
|
if([data isKindOfClass:[NSData class]]) {
|
||||||
|
jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:error];
|
||||||
|
} else {
|
||||||
|
jsonData = data;
|
||||||
|
}
|
||||||
|
if(!jsonData) {
|
||||||
|
jsonData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
||||||
|
} else if([jsonData isKindOfClass:[NSNull class]]) {
|
||||||
|
return nil;
|
||||||
|
}
|
||||||
|
|
||||||
// pure object
|
// pure object
|
||||||
if ([self.basicReturnTypes containsObject:className]) {
|
if ([self.basicReturnTypes containsObject:className]) {
|
||||||
return data;
|
return jsonData;
|
||||||
}
|
}
|
||||||
|
|
||||||
// primitives
|
// primitives
|
||||||
if ([self.primitiveTypes containsObject:className]) {
|
if ([self.primitiveTypes containsObject:className]) {
|
||||||
return [self deserializePrimitiveValue:data class:className error:error];
|
return [self deserializePrimitiveValue:jsonData class:className error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
NSTextCheckingResult *match = nil;
|
NSTextCheckingResult *match = nil;
|
||||||
@ -78,37 +94,37 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
|
|||||||
match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range];
|
match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range];
|
||||||
if (match) {
|
if (match) {
|
||||||
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
|
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
|
||||||
return [self deserializeArrayValue:data innerType:innerType error:error];
|
return [self deserializeArrayValue:jsonData innerType:innerType error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
// list of primitives
|
// list of primitives
|
||||||
match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range];
|
match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range];
|
||||||
if (match) {
|
if (match) {
|
||||||
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
|
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
|
||||||
return [self deserializeArrayValue:data innerType:innerType error:error];
|
return [self deserializeArrayValue:jsonData innerType:innerType error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
// map
|
// map
|
||||||
match = [self.dictPatExpression firstMatchInString:className options:0 range:range];
|
match = [self.dictPatExpression firstMatchInString:className options:0 range:range];
|
||||||
if (match) {
|
if (match) {
|
||||||
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
|
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
|
||||||
return [self deserializeDictionaryValue:data valueType:valueType error:error];
|
return [self deserializeDictionaryValue:jsonData valueType:valueType error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range];
|
match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range];
|
||||||
if (match) {
|
if (match) {
|
||||||
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
|
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
|
||||||
return [self deserializeDictionaryValue:data valueType:valueType error:error];
|
return [self deserializeDictionaryValue:jsonData valueType:valueType error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
// model
|
// model
|
||||||
Class ModelClass = NSClassFromString(className);
|
Class ModelClass = NSClassFromString(className);
|
||||||
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
|
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
|
||||||
return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error];
|
return [(JSONModel *) [ModelClass alloc] initWithDictionary:jsonData error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
if(error) {
|
if(error) {
|
||||||
*error = [self unknownResponseErrorWithExpectedType:className data:data];
|
*error = [self unknownResponseErrorWithExpectedType:className data:jsonData];
|
||||||
}
|
}
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
@ -172,7 +188,7 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
|
|||||||
|
|
||||||
- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error {
|
- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error {
|
||||||
if ([className isEqualToString:@"NSString"]) {
|
if ([className isEqualToString:@"NSString"]) {
|
||||||
return [NSString stringWithString:data];
|
return [NSString stringWithFormat:@"%@",data];
|
||||||
}
|
}
|
||||||
else if ([className isEqualToString:@"NSDate"]) {
|
else if ([className isEqualToString:@"NSDate"]) {
|
||||||
return [self deserializeDateValue:data error:error];
|
return [self deserializeDateValue:data error:error];
|
||||||
|
@ -26,6 +26,8 @@
|
|||||||
|
|
||||||
extern NSString * SWGPercentEscapedStringFromString(NSString *string);
|
extern NSString * SWGPercentEscapedStringFromString(NSString *string);
|
||||||
|
|
||||||
|
extern NSString * const kSWGApplicationJSONType;
|
||||||
|
|
||||||
@protocol SWGSanitizer <NSObject>
|
@protocol SWGSanitizer <NSObject>
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -3,6 +3,8 @@
|
|||||||
#import "SWGQueryParamCollection.h"
|
#import "SWGQueryParamCollection.h"
|
||||||
#import <ISO8601/ISO8601.h>
|
#import <ISO8601/ISO8601.h>
|
||||||
|
|
||||||
|
NSString * const kSWGApplicationJSONType = @"application/json";
|
||||||
|
|
||||||
NSString * SWGPercentEscapedStringFromString(NSString *string) {
|
NSString * SWGPercentEscapedStringFromString(NSString *string) {
|
||||||
static NSString * const kSWGCharactersGeneralDelimitersToEncode = @":#[]@";
|
static NSString * const kSWGCharactersGeneralDelimitersToEncode = @":#[]@";
|
||||||
static NSString * const kSWGCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
|
static NSString * const kSWGCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
|
||||||
@ -43,8 +45,6 @@ NSString * SWGPercentEscapedStringFromString(NSString *string) {
|
|||||||
|
|
||||||
@implementation SWGSanitizer
|
@implementation SWGSanitizer
|
||||||
|
|
||||||
static NSString * kApplicationJSONType = @"application/json";
|
|
||||||
|
|
||||||
-(instancetype)init {
|
-(instancetype)init {
|
||||||
self = [super init];
|
self = [super init];
|
||||||
if ( !self ) {
|
if ( !self ) {
|
||||||
@ -141,7 +141,7 @@ static NSString * kApplicationJSONType = @"application/json";
|
|||||||
NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]];
|
NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]];
|
||||||
for (NSString *string in accepts) {
|
for (NSString *string in accepts) {
|
||||||
if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) {
|
if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) {
|
||||||
return kApplicationJSONType;
|
return kSWGApplicationJSONType;
|
||||||
}
|
}
|
||||||
[lowerAccepts addObject:[string lowercaseString]];
|
[lowerAccepts addObject:[string lowercaseString]];
|
||||||
}
|
}
|
||||||
@ -153,12 +153,12 @@ static NSString * kApplicationJSONType = @"application/json";
|
|||||||
*/
|
*/
|
||||||
- (NSString *) selectHeaderContentType:(NSArray *)contentTypes {
|
- (NSString *) selectHeaderContentType:(NSArray *)contentTypes {
|
||||||
if (contentTypes.count == 0) {
|
if (contentTypes.count == 0) {
|
||||||
return kApplicationJSONType;
|
return kSWGApplicationJSONType;
|
||||||
}
|
}
|
||||||
NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]];
|
NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]];
|
||||||
for (NSString *string in contentTypes) {
|
for (NSString *string in contentTypes) {
|
||||||
if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){
|
if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){
|
||||||
return kApplicationJSONType;
|
return kSWGApplicationJSONType;
|
||||||
}
|
}
|
||||||
[lowerContentTypes addObject:[string lowercaseString]];
|
[lowerContentTypes addObject:[string lowercaseString]];
|
||||||
}
|
}
|
||||||
|
@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi
|
|||||||
|
|
||||||
- API version: 1.0.0
|
- API version: 1.0.0
|
||||||
- Package version:
|
- Package version:
|
||||||
- Build date: 2016-08-17T10:06:57.326+02:00
|
- Build date: 2016-08-23T10:56:26.470+02:00
|
||||||
- Build package: class io.swagger.codegen.languages.ObjcClientCodegen
|
- Build package: class io.swagger.codegen.languages.ObjcClientCodegen
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
@ -39,78 +39,19 @@ extern NSString *const SWGResponseObjectErrorKey;
|
|||||||
|
|
||||||
@property (nonatomic, strong, readonly) id<SWGConfiguration> configuration;
|
@property (nonatomic, strong, readonly) id<SWGConfiguration> configuration;
|
||||||
|
|
||||||
@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
|
|
||||||
@property(nonatomic, assign) NSTimeInterval timeoutInterval;
|
@property(nonatomic, assign) NSTimeInterval timeoutInterval;
|
||||||
@property(nonatomic, readonly) NSOperationQueue* queue;
|
|
||||||
|
|
||||||
@property(nonatomic, strong) id<SWGResponseDeserializer> responseDeserializer;
|
@property(nonatomic, strong) id<SWGResponseDeserializer> responseDeserializer;
|
||||||
|
|
||||||
@property(nonatomic, strong) id<SWGSanitizer> sanitizer;
|
@property(nonatomic, strong) id<SWGSanitizer> sanitizer;
|
||||||
/**
|
|
||||||
* Clears Cache
|
|
||||||
*/
|
|
||||||
+(void)clearCache;
|
|
||||||
|
|
||||||
/**
|
@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer <AFURLRequestSerialization> *>* requestSerializerForContentType;
|
||||||
* Turns on cache
|
|
||||||
*
|
|
||||||
* @param enabled If the cached is enable, must be `YES` or `NO`
|
|
||||||
*/
|
|
||||||
+(void)setCacheEnabled:(BOOL) enabled;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the client unreachable
|
|
||||||
*
|
|
||||||
* @param state off line state, must be `YES` or `NO`
|
|
||||||
*/
|
|
||||||
+(void) setOfflineState:(BOOL) state;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets if the client is unreachable
|
|
||||||
*
|
|
||||||
* @return The client offline state
|
|
||||||
*/
|
|
||||||
+(BOOL) getOfflineState;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the client reachability, this may be overridden by the reachability manager if reachability changes
|
|
||||||
*
|
|
||||||
* @param The client reachability.
|
|
||||||
*/
|
|
||||||
+(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the client reachability
|
|
||||||
*
|
|
||||||
* @return The client reachability.
|
|
||||||
*/
|
|
||||||
+(AFNetworkReachabilityStatus) getReachabilityStatus;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Customizes the behavior when the reachability changed
|
|
||||||
*
|
|
||||||
* @param changeBlock The block will be executed when the reachability changed.
|
|
||||||
*/
|
|
||||||
+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets client singleton instance
|
* Gets client singleton instance
|
||||||
*/
|
*/
|
||||||
+ (instancetype) sharedClient;
|
+ (instancetype) sharedClient;
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the api client reachability strategy
|
|
||||||
*/
|
|
||||||
- (void)configureCacheReachibility;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets header for request
|
|
||||||
*
|
|
||||||
* @param value The header value
|
|
||||||
* @param forKey The header key
|
|
||||||
*/
|
|
||||||
-(void)setHeaderValue:(NSString*) value
|
|
||||||
forKey:(NSString*) forKey;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Updates header parameters and query parameters for authentication
|
* Updates header parameters and query parameters for authentication
|
||||||
@ -119,9 +60,7 @@ extern NSString *const SWGResponseObjectErrorKey;
|
|||||||
* @param querys The query parameters will be updated, passed by pointer to pointer.
|
* @param querys The query parameters will be updated, passed by pointer to pointer.
|
||||||
* @param authSettings The authentication names NSArray.
|
* @param authSettings The authentication names NSArray.
|
||||||
*/
|
*/
|
||||||
- (void) updateHeaderParams:(NSDictionary **)headers
|
- (void) updateHeaderParams:(NSDictionary **)headers queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings;
|
||||||
queryParams:(NSDictionary **)querys
|
|
||||||
WithAuthSettings:(NSArray *)authSettings;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -131,6 +70,14 @@ extern NSString *const SWGResponseObjectErrorKey;
|
|||||||
*/
|
*/
|
||||||
- (instancetype)initWithConfiguration:(id<SWGConfiguration>)configuration;
|
- (instancetype)initWithConfiguration:(id<SWGConfiguration>)configuration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initializes the session manager with a configuration and url
|
||||||
|
*
|
||||||
|
* @param url The base url
|
||||||
|
* @param configuration The configuration implementation
|
||||||
|
*/
|
||||||
|
- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<SWGConfiguration>)configuration;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Performs request
|
* Performs request
|
||||||
*
|
*
|
||||||
@ -161,11 +108,4 @@ extern NSString *const SWGResponseObjectErrorKey;
|
|||||||
responseType: (NSString *) responseType
|
responseType: (NSString *) responseType
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock;
|
completionBlock: (void (^)(id, NSError *))completionBlock;
|
||||||
|
|
||||||
/**
|
|
||||||
* Custom security policy
|
|
||||||
*
|
|
||||||
* @return AFSecurityPolicy
|
|
||||||
*/
|
|
||||||
- (AFSecurityPolicy *) customSecurityPolicy;
|
|
||||||
|
|
||||||
@end
|
@end
|
||||||
|
@ -1,21 +1,13 @@
|
|||||||
#import <ISO8601/NSDate+ISO8601.h>
|
|
||||||
|
|
||||||
#import "SWGLogger.h"
|
#import "SWGLogger.h"
|
||||||
#import "SWGApiClient.h"
|
#import "SWGApiClient.h"
|
||||||
#import "SWGJSONRequestSerializer.h"
|
#import "SWGJSONRequestSerializer.h"
|
||||||
#import "SWGJSONResponseSerializer.h"
|
|
||||||
#import "SWGQueryParamCollection.h"
|
#import "SWGQueryParamCollection.h"
|
||||||
#import "SWGDefaultConfiguration.h"
|
#import "SWGDefaultConfiguration.h"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject";
|
NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject";
|
||||||
|
|
||||||
static bool offlineState = false;
|
static NSString * const kSWGContentDispositionKey = @"Content-Disposition";
|
||||||
static bool cacheEnabled = false;
|
|
||||||
static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable;
|
|
||||||
static void (^reachabilityChangeBlock)(int);
|
|
||||||
|
|
||||||
|
|
||||||
static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) {
|
static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) {
|
||||||
if(![response isKindOfClass:[NSHTTPURLResponse class]]) {
|
if(![response isKindOfClass:[NSHTTPURLResponse class]]) {
|
||||||
@ -26,17 +18,13 @@ static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) {
|
|||||||
|
|
||||||
static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
||||||
NSDictionary * headers = SWG__headerFieldsForResponse(response);
|
NSDictionary * headers = SWG__headerFieldsForResponse(response);
|
||||||
if(!headers[@"Content-Disposition"]) {
|
if(!headers[kSWGContentDispositionKey]) {
|
||||||
return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
|
return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
|
||||||
}
|
}
|
||||||
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?";
|
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?";
|
||||||
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern
|
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
|
||||||
options:NSRegularExpressionCaseInsensitive
|
NSString *contentDispositionHeader = headers[kSWGContentDispositionKey];
|
||||||
error:nil];
|
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader options:0 range:NSMakeRange(0, [contentDispositionHeader length])];
|
||||||
NSString *contentDispositionHeader = headers[@"Content-Disposition"];
|
|
||||||
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader
|
|
||||||
options:0
|
|
||||||
range:NSMakeRange(0, [contentDispositionHeader length])];
|
|
||||||
return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]];
|
return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -45,6 +33,8 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
|
|
||||||
@property (nonatomic, strong, readwrite) id<SWGConfiguration> configuration;
|
@property (nonatomic, strong, readwrite) id<SWGConfiguration> configuration;
|
||||||
|
|
||||||
|
@property (nonatomic, strong) NSArray<NSString*>* downloadTaskResponseTypes;
|
||||||
|
|
||||||
@end
|
@end
|
||||||
|
|
||||||
@implementation SWGApiClient
|
@implementation SWGApiClient
|
||||||
@ -75,7 +65,6 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<SWGConfiguration>)configuration {
|
- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<SWGConfiguration>)configuration {
|
||||||
|
|
||||||
self = [super initWithBaseURL:url];
|
self = [super initWithBaseURL:url];
|
||||||
if (self) {
|
if (self) {
|
||||||
_configuration = configuration;
|
_configuration = configuration;
|
||||||
@ -83,102 +72,30 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
_responseDeserializer = [[SWGResponseDeserializer alloc] init];
|
_responseDeserializer = [[SWGResponseDeserializer alloc] init];
|
||||||
_sanitizer = [[SWGSanitizer alloc] init];
|
_sanitizer = [[SWGSanitizer alloc] init];
|
||||||
|
|
||||||
self.requestSerializer = [AFJSONRequestSerializer serializer];
|
_downloadTaskResponseTypes = @[@"NSURL*", @"NSURL"];
|
||||||
self.responseSerializer = [AFJSONResponseSerializer serializer];
|
|
||||||
self.securityPolicy = [self customSecurityPolicy];
|
|
||||||
|
|
||||||
// configure reachability
|
AFHTTPRequestSerializer* afhttpRequestSerializer = [AFHTTPRequestSerializer serializer];
|
||||||
[self configureCacheReachibility];
|
SWGJSONRequestSerializer * swgjsonRequestSerializer = [SWGJSONRequestSerializer serializer];
|
||||||
|
_requestSerializerForContentType = @{kSWGApplicationJSONType : swgjsonRequestSerializer,
|
||||||
|
@"application/x-www-form-urlencoded": afhttpRequestSerializer,
|
||||||
|
@"multipart/form-data": afhttpRequestSerializer
|
||||||
|
};
|
||||||
|
self.securityPolicy = [self createSecurityPolicy];
|
||||||
|
self.responseSerializer = [AFHTTPResponseSerializer serializer];
|
||||||
}
|
}
|
||||||
|
|
||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
#pragma mark - Setter Methods
|
|
||||||
|
|
||||||
+ (void) setOfflineState:(BOOL) state {
|
|
||||||
offlineState = state;
|
|
||||||
}
|
|
||||||
|
|
||||||
+ (void) setCacheEnabled:(BOOL)enabled {
|
|
||||||
cacheEnabled = enabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status {
|
|
||||||
reachabilityStatus = status;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey {
|
|
||||||
[self.requestSerializer setValue:value forHTTPHeaderField:forKey];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)setRequestSerializer:(AFHTTPRequestSerializer<AFURLRequestSerialization> *)requestSerializer {
|
|
||||||
[super setRequestSerializer:requestSerializer];
|
|
||||||
requestSerializer.timeoutInterval = self.timeoutInterval;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Cache Methods
|
|
||||||
|
|
||||||
+(void)clearCache {
|
|
||||||
[[NSURLCache sharedURLCache] removeAllCachedResponses];
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize
|
|
||||||
diskSize: (unsigned long) diskSize {
|
|
||||||
NSAssert(memorySize > 0, @"invalid in-memory cache size");
|
|
||||||
NSAssert(diskSize >= 0, @"invalid disk cache size");
|
|
||||||
|
|
||||||
NSURLCache *cache =
|
|
||||||
[[NSURLCache alloc]
|
|
||||||
initWithMemoryCapacity:memorySize
|
|
||||||
diskCapacity:diskSize
|
|
||||||
diskPath:@"swagger_url_cache"];
|
|
||||||
|
|
||||||
[NSURLCache setSharedURLCache:cache];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Reachability Methods
|
|
||||||
|
|
||||||
+(AFNetworkReachabilityStatus) getReachabilityStatus {
|
|
||||||
return reachabilityStatus;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(BOOL) getOfflineState {
|
|
||||||
return offlineState;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock {
|
|
||||||
reachabilityChangeBlock = changeBlock;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) configureCacheReachibility {
|
|
||||||
[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
|
|
||||||
reachabilityStatus = status;
|
|
||||||
SWGDebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status));
|
|
||||||
[SWGApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable];
|
|
||||||
|
|
||||||
// call the reachability block, if configured
|
|
||||||
if (reachabilityChangeBlock != nil) {
|
|
||||||
reachabilityChangeBlock(status);
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
|
|
||||||
[self.reachabilityManager startMonitoring];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Task Methods
|
#pragma mark - Task Methods
|
||||||
|
|
||||||
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request
|
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock {
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
|
||||||
|
|
||||||
NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
|
NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
|
||||||
SWGDebugLogResponse(response, responseObject,request,error);
|
SWGDebugLogResponse(response, responseObject,request,error);
|
||||||
|
|
||||||
if(!error) {
|
if(!error) {
|
||||||
completionBlock(responseObject, nil);
|
completionBlock(responseObject, nil);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
|
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
|
||||||
if (responseObject) {
|
if (responseObject) {
|
||||||
// Add in the (parsed) response body.
|
// Add in the (parsed) response body.
|
||||||
@ -191,10 +108,9 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
return task;
|
return task;
|
||||||
}
|
}
|
||||||
|
|
||||||
- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request
|
- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock {
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
|
||||||
|
__block NSString * tempFolderPath = [self.configuration.tempFolderPath copy];
|
||||||
id<SWGConfiguration> config = self.configuration;
|
|
||||||
|
|
||||||
NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
|
NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
|
||||||
SWGDebugLogResponse(response, responseObject,request,error);
|
SWGDebugLogResponse(response, responseObject,request,error);
|
||||||
@ -206,9 +122,10 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
}
|
}
|
||||||
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
|
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
|
||||||
completionBlock(nil, augmentedError);
|
completionBlock(nil, augmentedError);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory();
|
NSString *directory = tempFolderPath ?: NSTemporaryDirectory();
|
||||||
NSString *filename = SWG__fileNameForResponse(response);
|
NSString *filename = SWG__fileNameForResponse(response);
|
||||||
|
|
||||||
NSString *filepath = [directory stringByAppendingPathComponent:filename];
|
NSString *filepath = [directory stringByAppendingPathComponent:filename];
|
||||||
@ -238,35 +155,17 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
responseType: (NSString *) responseType
|
responseType: (NSString *) responseType
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
completionBlock: (void (^)(id, NSError *))completionBlock {
|
||||||
|
|
||||||
// setting request serializer
|
AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer = [self requestSerializerForRequestContentType:requestContentType];
|
||||||
if ([requestContentType isEqualToString:@"application/json"]) {
|
|
||||||
self.requestSerializer = [SWGJSONRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else if ([requestContentType isEqualToString:@"multipart/form-data"]) {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
NSAssert(NO, @"Unsupported request type %@", requestContentType);
|
|
||||||
}
|
|
||||||
|
|
||||||
// setting response serializer
|
__weak id<SWGSanitizer> sanitizer = self.sanitizer;
|
||||||
if ([responseContentType isEqualToString:@"application/json"]) {
|
|
||||||
self.responseSerializer = [SWGJSONResponseSerializer serializer];
|
|
||||||
} else {
|
|
||||||
self.responseSerializer = [AFHTTPResponseSerializer serializer];
|
|
||||||
}
|
|
||||||
|
|
||||||
// sanitize parameters
|
// sanitize parameters
|
||||||
pathParams = [self.sanitizer sanitizeForSerialization:pathParams];
|
pathParams = [sanitizer sanitizeForSerialization:pathParams];
|
||||||
queryParams = [self.sanitizer sanitizeForSerialization:queryParams];
|
queryParams = [sanitizer sanitizeForSerialization:queryParams];
|
||||||
headerParams = [self.sanitizer sanitizeForSerialization:headerParams];
|
headerParams = [sanitizer sanitizeForSerialization:headerParams];
|
||||||
formParams = [self.sanitizer sanitizeForSerialization:formParams];
|
formParams = [sanitizer sanitizeForSerialization:formParams];
|
||||||
if(![body isKindOfClass:[NSData class]]) {
|
if(![body isKindOfClass:[NSData class]]) {
|
||||||
body = [self.sanitizer sanitizeForSerialization:body];
|
body = [sanitizer sanitizeForSerialization:body];
|
||||||
}
|
}
|
||||||
|
|
||||||
// auth setting
|
// auth setting
|
||||||
@ -279,22 +178,19 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
[resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString];
|
[resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString];
|
||||||
}];
|
}];
|
||||||
|
|
||||||
NSMutableURLRequest * request = nil;
|
|
||||||
|
|
||||||
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams];
|
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams];
|
||||||
if ([pathWithQueryParams hasPrefix:@"/"]) {
|
if ([pathWithQueryParams hasPrefix:@"/"]) {
|
||||||
pathWithQueryParams = [pathWithQueryParams substringFromIndex:1];
|
pathWithQueryParams = [pathWithQueryParams substringFromIndex:1];
|
||||||
}
|
}
|
||||||
|
|
||||||
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
|
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
|
||||||
|
|
||||||
|
NSError *requestCreateError = nil;
|
||||||
|
NSMutableURLRequest * request = nil;
|
||||||
if (files.count > 0) {
|
if (files.count > 0) {
|
||||||
__weak __typeof(self)weakSelf = self;
|
request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
|
||||||
request = [self.requestSerializer multipartFormRequestWithMethod:@"POST"
|
|
||||||
URLString:urlString
|
|
||||||
parameters:nil
|
|
||||||
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
|
|
||||||
[formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
[formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
||||||
NSString *objString = [weakSelf.sanitizer parameterToString:obj];
|
NSString *objString = [sanitizer parameterToString:obj];
|
||||||
NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding];
|
NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding];
|
||||||
[formData appendPartWithFormData:data name:key];
|
[formData appendPartWithFormData:data name:key];
|
||||||
}];
|
}];
|
||||||
@ -302,59 +198,43 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
NSURL *filePath = (NSURL *)obj;
|
NSURL *filePath = (NSURL *)obj;
|
||||||
[formData appendPartWithFileURL:filePath name:key error:nil];
|
[formData appendPartWithFileURL:filePath name:key error:nil];
|
||||||
}];
|
}];
|
||||||
} error:nil];
|
} error:&requestCreateError];
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
if (formParams) {
|
if (formParams) {
|
||||||
request = [self.requestSerializer requestWithMethod:method
|
request = [requestSerializer requestWithMethod:method URLString:urlString parameters:formParams error:&requestCreateError];
|
||||||
URLString:urlString
|
|
||||||
parameters:formParams
|
|
||||||
error:nil];
|
|
||||||
}
|
}
|
||||||
if (body) {
|
if (body) {
|
||||||
request = [self.requestSerializer requestWithMethod:method
|
request = [requestSerializer requestWithMethod:method URLString:urlString parameters:body error:&requestCreateError];
|
||||||
URLString:urlString
|
|
||||||
parameters:body
|
|
||||||
error:nil];
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if(!request) {
|
||||||
// request cache
|
completionBlock(nil, requestCreateError);
|
||||||
BOOL hasHeaderParams = [headerParams count] > 0;
|
return nil;
|
||||||
if (offlineState) {
|
|
||||||
SWGDebugLog(@"%@ cache forced", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
|
|
||||||
}
|
|
||||||
else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) {
|
|
||||||
SWGDebugLog(@"%@ cache enabled", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
SWGDebugLog(@"%@ cache disabled", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hasHeaderParams){
|
if ([headerParams count] > 0){
|
||||||
for(NSString * key in [headerParams keyEnumerator]){
|
for(NSString * key in [headerParams keyEnumerator]){
|
||||||
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
|
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
[self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
|
[requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
|
||||||
|
|
||||||
[self postProcessRequest:request];
|
[self postProcessRequest:request];
|
||||||
|
|
||||||
|
|
||||||
NSURLSessionTask *task = nil;
|
NSURLSessionTask *task = nil;
|
||||||
|
|
||||||
if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) {
|
if ([self.downloadTaskResponseTypes containsObject:responseType]) {
|
||||||
task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
||||||
completionBlock(data, error);
|
completionBlock(data, error);
|
||||||
}];
|
}];
|
||||||
}
|
} else {
|
||||||
else {
|
__weak typeof(self) weakSelf = self;
|
||||||
task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
||||||
NSError * serializationError;
|
NSError * serializationError;
|
||||||
id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError];
|
id response = [weakSelf.responseDeserializer deserialize:data class:responseType error:&serializationError];
|
||||||
|
|
||||||
if(!response && !error){
|
if(!response && !error){
|
||||||
error = serializationError;
|
error = serializationError;
|
||||||
}
|
}
|
||||||
@ -367,16 +247,24 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
return task;
|
return task;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
-(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializerForRequestContentType:(NSString *)requestContentType {
|
||||||
|
AFHTTPRequestSerializer <AFURLRequestSerialization> * serializer = self.requestSerializerForContentType[requestContentType];
|
||||||
|
if(!serializer) {
|
||||||
|
NSAssert(NO, @"Unsupported request content type %@", requestContentType);
|
||||||
|
serializer = [AFHTTPRequestSerializer serializer];
|
||||||
|
}
|
||||||
|
serializer.timeoutInterval = self.timeoutInterval;
|
||||||
|
return serializer;
|
||||||
|
}
|
||||||
|
|
||||||
//Added for easier override to modify request
|
//Added for easier override to modify request
|
||||||
-(void)postProcessRequest:(NSMutableURLRequest *)request {
|
-(void)postProcessRequest:(NSMutableURLRequest *)request {
|
||||||
// Always disable cookies!
|
|
||||||
[request setHTTPShouldHandleCookies:NO];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#pragma mark -
|
#pragma mark -
|
||||||
|
|
||||||
- (NSString*) pathWithQueryParamsToString:(NSString*) path
|
- (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams {
|
||||||
queryParams:(NSDictionary*) queryParams {
|
|
||||||
if(queryParams.count == 0) {
|
if(queryParams.count == 0) {
|
||||||
return path;
|
return path;
|
||||||
}
|
}
|
||||||
@ -434,9 +322,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
/**
|
/**
|
||||||
* Update header and query params based on authentication settings
|
* Update header and query params based on authentication settings
|
||||||
*/
|
*/
|
||||||
- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers
|
- (void) updateHeaderParams:(NSDictionary * *)headers queryParams:(NSDictionary * *)querys WithAuthSettings:(NSArray *)authSettings {
|
||||||
queryParams:(NSDictionary *__autoreleasing *)querys
|
|
||||||
WithAuthSettings:(NSArray *)authSettings {
|
|
||||||
|
|
||||||
if ([authSettings count] == 0) {
|
if ([authSettings count] == 0) {
|
||||||
return;
|
return;
|
||||||
@ -466,7 +352,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
|
|||||||
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
|
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
|
||||||
}
|
}
|
||||||
|
|
||||||
- (AFSecurityPolicy *) customSecurityPolicy {
|
- (AFSecurityPolicy *) createSecurityPolicy {
|
||||||
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
|
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
|
||||||
|
|
||||||
id<SWGConfiguration> config = self.configuration;
|
id<SWGConfiguration> config = self.configuration;
|
||||||
|
@ -36,7 +36,7 @@
|
|||||||
_mutableApiKey = [NSMutableDictionary dictionary];
|
_mutableApiKey = [NSMutableDictionary dictionary];
|
||||||
_mutableApiKeyPrefix = [NSMutableDictionary dictionary];
|
_mutableApiKeyPrefix = [NSMutableDictionary dictionary];
|
||||||
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
|
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
|
||||||
;
|
|
||||||
_logger = [SWGLogger sharedLogger];
|
_logger = [SWGLogger sharedLogger];
|
||||||
}
|
}
|
||||||
return self;
|
return self;
|
||||||
@ -129,8 +129,6 @@
|
|||||||
self.logger.enabled = debug;
|
self.logger.enabled = debug;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key {
|
- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key {
|
||||||
if(!value) {
|
if(!value) {
|
||||||
[self.mutableDefaultHeaders removeObjectForKey:key];
|
[self.mutableDefaultHeaders removeObjectForKey:key];
|
||||||
|
@ -1,30 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <AFNetworking/AFURLResponseSerialization.h>
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Swagger Petstore
|
|
||||||
* This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters
|
|
||||||
*
|
|
||||||
* OpenAPI spec version: 1.0.0
|
|
||||||
* Contact: apiteam@wordnik.com
|
|
||||||
*
|
|
||||||
* NOTE: This class is auto generated by the swagger code generator program.
|
|
||||||
* https://github.com/swagger-api/swagger-codegen.git
|
|
||||||
* Do not edit the class manually.
|
|
||||||
*
|
|
||||||
* 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.
|
|
||||||
*/
|
|
||||||
|
|
||||||
@interface SWGJSONResponseSerializer : AFJSONResponseSerializer
|
|
||||||
|
|
||||||
@end
|
|
@ -1,39 +0,0 @@
|
|||||||
#import "SWGJSONResponseSerializer.h"
|
|
||||||
|
|
||||||
@implementation SWGJSONResponseSerializer
|
|
||||||
|
|
||||||
///
|
|
||||||
/// When customize a response serializer,
|
|
||||||
/// the serializer must conform the protocol `AFURLResponseSerialization`
|
|
||||||
/// and implements the protocol method `responseObjectForResponse:error:`
|
|
||||||
///
|
|
||||||
/// @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.
|
|
||||||
///
|
|
||||||
- (id) responseObjectForResponse:(NSURLResponse *)response
|
|
||||||
data:(NSData *)data
|
|
||||||
error:(NSError *__autoreleasing *)error {
|
|
||||||
NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error];
|
|
||||||
|
|
||||||
// if response data is not a valid json, return string of data.
|
|
||||||
if ([self isParseError:*error]) {
|
|
||||||
*error = nil;
|
|
||||||
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
|
||||||
return responseString;
|
|
||||||
}
|
|
||||||
|
|
||||||
return responseJson;
|
|
||||||
}
|
|
||||||
|
|
||||||
-(BOOL)isParseError:(NSError *)error {
|
|
||||||
return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840;
|
|
||||||
}
|
|
||||||
|
|
||||||
+ (instancetype)serializer {
|
|
||||||
return [self serializerWithReadingOptions:NSJSONReadingAllowFragments];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -17,8 +17,7 @@
|
|||||||
|
|
||||||
#pragma mark - Log Methods
|
#pragma mark - Log Methods
|
||||||
|
|
||||||
- (void)debugLog:(NSString *)method
|
- (void)debugLog:(NSString *)method message:(NSString *)format, ... {
|
||||||
message:(NSString *)format, ... {
|
|
||||||
if (!self.isEnabled) {
|
if (!self.isEnabled) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -16,6 +16,7 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
|
|||||||
@property (nonatomic, strong) NSNumberFormatter* numberFormatter;
|
@property (nonatomic, strong) NSNumberFormatter* numberFormatter;
|
||||||
@property (nonatomic, strong) NSArray *primitiveTypes;
|
@property (nonatomic, strong) NSArray *primitiveTypes;
|
||||||
@property (nonatomic, strong) NSArray *basicReturnTypes;
|
@property (nonatomic, strong) NSArray *basicReturnTypes;
|
||||||
|
@property (nonatomic, strong) NSArray *dataReturnTypes;
|
||||||
|
|
||||||
@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression;
|
@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression;
|
||||||
@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression;
|
@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression;
|
||||||
@ -33,7 +34,9 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
|
|||||||
formatter.numberStyle = NSNumberFormatterDecimalStyle;
|
formatter.numberStyle = NSNumberFormatterDecimalStyle;
|
||||||
_numberFormatter = formatter;
|
_numberFormatter = formatter;
|
||||||
_primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"];
|
_primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"];
|
||||||
_basicReturnTypes = @[@"NSObject", @"id", @"NSData"];
|
_basicReturnTypes = @[@"NSObject", @"id"];
|
||||||
|
_dataReturnTypes = @[@"NSData"];
|
||||||
|
|
||||||
_arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>"
|
_arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>"
|
||||||
options:NSRegularExpressionCaseInsensitive
|
options:NSRegularExpressionCaseInsensitive
|
||||||
error:nil];
|
error:nil];
|
||||||
@ -53,23 +56,36 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
|
|||||||
#pragma mark - Deserialize methods
|
#pragma mark - Deserialize methods
|
||||||
|
|
||||||
- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error {
|
- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error {
|
||||||
// return nil if data is nil or className is nil
|
if (!data || !className) {
|
||||||
if (!data || !className || [data isKindOfClass:[NSNull class]]) {
|
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove "*" from className, if ends with "*"
|
|
||||||
if ([className hasSuffix:@"*"]) {
|
if ([className hasSuffix:@"*"]) {
|
||||||
className = [className substringToIndex:[className length] - 1];
|
className = [className substringToIndex:[className length] - 1];
|
||||||
}
|
}
|
||||||
|
if([self.dataReturnTypes containsObject:className]) {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
id jsonData = nil;
|
||||||
|
if([data isKindOfClass:[NSData class]]) {
|
||||||
|
jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:error];
|
||||||
|
} else {
|
||||||
|
jsonData = data;
|
||||||
|
}
|
||||||
|
if(!jsonData) {
|
||||||
|
jsonData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
||||||
|
} else if([jsonData isKindOfClass:[NSNull class]]) {
|
||||||
|
return nil;
|
||||||
|
}
|
||||||
|
|
||||||
// pure object
|
// pure object
|
||||||
if ([self.basicReturnTypes containsObject:className]) {
|
if ([self.basicReturnTypes containsObject:className]) {
|
||||||
return data;
|
return jsonData;
|
||||||
}
|
}
|
||||||
|
|
||||||
// primitives
|
// primitives
|
||||||
if ([self.primitiveTypes containsObject:className]) {
|
if ([self.primitiveTypes containsObject:className]) {
|
||||||
return [self deserializePrimitiveValue:data class:className error:error];
|
return [self deserializePrimitiveValue:jsonData class:className error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
NSTextCheckingResult *match = nil;
|
NSTextCheckingResult *match = nil;
|
||||||
@ -78,37 +94,37 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
|
|||||||
match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range];
|
match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range];
|
||||||
if (match) {
|
if (match) {
|
||||||
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
|
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
|
||||||
return [self deserializeArrayValue:data innerType:innerType error:error];
|
return [self deserializeArrayValue:jsonData innerType:innerType error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
// list of primitives
|
// list of primitives
|
||||||
match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range];
|
match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range];
|
||||||
if (match) {
|
if (match) {
|
||||||
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
|
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
|
||||||
return [self deserializeArrayValue:data innerType:innerType error:error];
|
return [self deserializeArrayValue:jsonData innerType:innerType error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
// map
|
// map
|
||||||
match = [self.dictPatExpression firstMatchInString:className options:0 range:range];
|
match = [self.dictPatExpression firstMatchInString:className options:0 range:range];
|
||||||
if (match) {
|
if (match) {
|
||||||
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
|
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
|
||||||
return [self deserializeDictionaryValue:data valueType:valueType error:error];
|
return [self deserializeDictionaryValue:jsonData valueType:valueType error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range];
|
match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range];
|
||||||
if (match) {
|
if (match) {
|
||||||
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
|
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
|
||||||
return [self deserializeDictionaryValue:data valueType:valueType error:error];
|
return [self deserializeDictionaryValue:jsonData valueType:valueType error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
// model
|
// model
|
||||||
Class ModelClass = NSClassFromString(className);
|
Class ModelClass = NSClassFromString(className);
|
||||||
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
|
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
|
||||||
return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error];
|
return [(JSONModel *) [ModelClass alloc] initWithDictionary:jsonData error:error];
|
||||||
}
|
}
|
||||||
|
|
||||||
if(error) {
|
if(error) {
|
||||||
*error = [self unknownResponseErrorWithExpectedType:className data:data];
|
*error = [self unknownResponseErrorWithExpectedType:className data:jsonData];
|
||||||
}
|
}
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
@ -172,7 +188,7 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
|
|||||||
|
|
||||||
- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error {
|
- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error {
|
||||||
if ([className isEqualToString:@"NSString"]) {
|
if ([className isEqualToString:@"NSString"]) {
|
||||||
return [NSString stringWithString:data];
|
return [NSString stringWithFormat:@"%@",data];
|
||||||
}
|
}
|
||||||
else if ([className isEqualToString:@"NSDate"]) {
|
else if ([className isEqualToString:@"NSDate"]) {
|
||||||
return [self deserializeDateValue:data error:error];
|
return [self deserializeDateValue:data error:error];
|
||||||
|
@ -26,6 +26,8 @@
|
|||||||
|
|
||||||
extern NSString * SWGPercentEscapedStringFromString(NSString *string);
|
extern NSString * SWGPercentEscapedStringFromString(NSString *string);
|
||||||
|
|
||||||
|
extern NSString * const kSWGApplicationJSONType;
|
||||||
|
|
||||||
@protocol SWGSanitizer <NSObject>
|
@protocol SWGSanitizer <NSObject>
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -3,6 +3,8 @@
|
|||||||
#import "SWGQueryParamCollection.h"
|
#import "SWGQueryParamCollection.h"
|
||||||
#import <ISO8601/ISO8601.h>
|
#import <ISO8601/ISO8601.h>
|
||||||
|
|
||||||
|
NSString * const kSWGApplicationJSONType = @"application/json";
|
||||||
|
|
||||||
NSString * SWGPercentEscapedStringFromString(NSString *string) {
|
NSString * SWGPercentEscapedStringFromString(NSString *string) {
|
||||||
static NSString * const kSWGCharactersGeneralDelimitersToEncode = @":#[]@";
|
static NSString * const kSWGCharactersGeneralDelimitersToEncode = @":#[]@";
|
||||||
static NSString * const kSWGCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
|
static NSString * const kSWGCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
|
||||||
@ -43,8 +45,6 @@ NSString * SWGPercentEscapedStringFromString(NSString *string) {
|
|||||||
|
|
||||||
@implementation SWGSanitizer
|
@implementation SWGSanitizer
|
||||||
|
|
||||||
static NSString * kApplicationJSONType = @"application/json";
|
|
||||||
|
|
||||||
-(instancetype)init {
|
-(instancetype)init {
|
||||||
self = [super init];
|
self = [super init];
|
||||||
if ( !self ) {
|
if ( !self ) {
|
||||||
@ -141,7 +141,7 @@ static NSString * kApplicationJSONType = @"application/json";
|
|||||||
NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]];
|
NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]];
|
||||||
for (NSString *string in accepts) {
|
for (NSString *string in accepts) {
|
||||||
if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) {
|
if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) {
|
||||||
return kApplicationJSONType;
|
return kSWGApplicationJSONType;
|
||||||
}
|
}
|
||||||
[lowerAccepts addObject:[string lowercaseString]];
|
[lowerAccepts addObject:[string lowercaseString]];
|
||||||
}
|
}
|
||||||
@ -153,12 +153,12 @@ static NSString * kApplicationJSONType = @"application/json";
|
|||||||
*/
|
*/
|
||||||
- (NSString *) selectHeaderContentType:(NSArray *)contentTypes {
|
- (NSString *) selectHeaderContentType:(NSArray *)contentTypes {
|
||||||
if (contentTypes.count == 0) {
|
if (contentTypes.count == 0) {
|
||||||
return kApplicationJSONType;
|
return kSWGApplicationJSONType;
|
||||||
}
|
}
|
||||||
NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]];
|
NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]];
|
||||||
for (NSString *string in contentTypes) {
|
for (NSString *string in contentTypes) {
|
||||||
if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){
|
if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){
|
||||||
return kApplicationJSONType;
|
return kSWGApplicationJSONType;
|
||||||
}
|
}
|
||||||
[lowerContentTypes addObject:[string lowercaseString]];
|
[lowerContentTypes addObject:[string lowercaseString]];
|
||||||
}
|
}
|
||||||
|
@ -250,4 +250,16 @@
|
|||||||
XCTAssertTrue([result isEqual:@NO]);
|
XCTAssertTrue([result isEqual:@NO]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
- (void)testDeserializeStringData {
|
||||||
|
NSString *data = @"1233";
|
||||||
|
|
||||||
|
NSError* error;
|
||||||
|
NSString * returnValue = [apiClient.responseDeserializer deserialize:[data dataUsingEncoding:NSUTF8StringEncoding] class:@"NSString*" error:&error];
|
||||||
|
XCTAssertTrue([returnValue isEqual:data]);
|
||||||
|
|
||||||
|
NSNumber *returnNumber = [apiClient.responseDeserializer deserialize:[data dataUsingEncoding:NSUTF8StringEncoding] class:@"NSNumber*" error:&error];
|
||||||
|
XCTAssertTrue([returnNumber isEqual:@1233]);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@end
|
@end
|
||||||
|
@ -30,14 +30,7 @@
|
|||||||
if (!output) {
|
if (!output) {
|
||||||
XCTFail(@"response can't be nil");
|
XCTFail(@"response can't be nil");
|
||||||
}
|
}
|
||||||
|
XCTAssertTrue([output rangeOfString:@"logged in user"].location != NSNotFound);
|
||||||
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"logged in user"
|
|
||||||
options:0
|
|
||||||
error:nil];
|
|
||||||
NSTextCheckingResult *match = [regex firstMatchInString:output
|
|
||||||
options:0
|
|
||||||
range:NSMakeRange(0, [output length])];
|
|
||||||
XCTAssertNotNil(match);
|
|
||||||
[expectation fulfill];
|
[expectation fulfill];
|
||||||
}];
|
}];
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user