Fix problem with multitheard api client

This commit is contained in:
Mateusz Maćkowiak 2016-08-23 14:12:58 +02:00
parent a893168291
commit e40f9abdbb
30 changed files with 343 additions and 933 deletions

View File

@ -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-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m"));
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("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h"));
supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m"));
supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.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("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m"));

View File

@ -1,21 +1,13 @@
#import <ISO8601/NSDate+ISO8601.h>
#import "{{classPrefix}}Logger.h"
#import "{{classPrefix}}ApiClient.h"
#import "{{classPrefix}}JSONRequestSerializer.h"
#import "{{classPrefix}}JSONResponseSerializer.h"
#import "{{classPrefix}}QueryParamCollection.h"
#import "{{classPrefix}}DefaultConfiguration.h"
NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject";
static bool offlineState = false;
static bool cacheEnabled = false;
static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable;
static void (^reachabilityChangeBlock)(int);
static NSString * const k{{classPrefix}}ContentDispositionKey = @"Content-Disposition";
static NSDictionary * {{classPrefix}}__headerFieldsForResponse(NSURLResponse *response) {
if(![response isKindOfClass:[NSHTTPURLResponse class]]) {
@ -26,17 +18,13 @@ static NSDictionary * {{classPrefix}}__headerFieldsForResponse(NSURLResponse *re
static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) {
NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response);
if(!headers[@"Content-Disposition"]) {
if(!headers[k{{classPrefix}}ContentDispositionKey]) {
return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
}
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?";
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *contentDispositionHeader = headers[@"Content-Disposition"];
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader
options:0
range:NSMakeRange(0, [contentDispositionHeader length])];
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
NSString *contentDispositionHeader = headers[k{{classPrefix}}ContentDispositionKey];
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader options:0 range:NSMakeRange(0, [contentDispositionHeader length])];
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) NSArray<NSString*>* downloadTaskResponseTypes;
@end
@implementation {{classPrefix}}ApiClient
@ -75,7 +65,6 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
}
- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<{{classPrefix}}Configuration>)configuration {
self = [super initWithBaseURL:url];
if (self) {
_configuration = configuration;
@ -83,102 +72,30 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
_responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init];
_sanitizer = [[{{classPrefix}}Sanitizer alloc] init];
self.requestSerializer = [AFJSONRequestSerializer serializer];
self.responseSerializer = [AFJSONResponseSerializer serializer];
self.securityPolicy = [self customSecurityPolicy];
_downloadTaskResponseTypes = @[@"NSURL*", @"NSURL"];
// configure reachability
[self configureCacheReachibility];
AFHTTPRequestSerializer* afhttpRequestSerializer = [AFHTTPRequestSerializer serializer];
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;
}
#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
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request
completionBlock: (void (^)(id, NSError *))completionBlock {
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock {
NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
{{classPrefix}}DebugLogResponse(response, responseObject,request,error);
if(!error) {
completionBlock(responseObject, nil);
return;
}
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
if (responseObject) {
// Add in the (parsed) response body.
@ -191,10 +108,9 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
return task;
}
- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request
completionBlock: (void (^)(id, NSError *))completionBlock {
id<{{classPrefix}}Configuration> config = self.configuration;
- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock {
__block NSString * tempFolderPath = [self.configuration.tempFolderPath copy];
NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *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];
completionBlock(nil, augmentedError);
return;
}
NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory();
NSString *directory = tempFolderPath ?: NSTemporaryDirectory();
NSString *filename = {{classPrefix}}__fileNameForResponse(response);
NSString *filepath = [directory stringByAppendingPathComponent:filename];
@ -238,35 +155,17 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
responseType: (NSString *) responseType
completionBlock: (void (^)(id, NSError *))completionBlock {
// setting request serializer
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);
}
AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer = [self requestSerializerForRequestContentType:requestContentType];
// setting response serializer
if ([responseContentType isEqualToString:@"application/json"]) {
self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer];
} else {
self.responseSerializer = [AFHTTPResponseSerializer serializer];
}
__weak id<SWGSanitizer> sanitizer = self.sanitizer;
// sanitize parameters
pathParams = [self.sanitizer sanitizeForSerialization:pathParams];
queryParams = [self.sanitizer sanitizeForSerialization:queryParams];
headerParams = [self.sanitizer sanitizeForSerialization:headerParams];
formParams = [self.sanitizer sanitizeForSerialization:formParams];
pathParams = [sanitizer sanitizeForSerialization:pathParams];
queryParams = [sanitizer sanitizeForSerialization:queryParams];
headerParams = [sanitizer sanitizeForSerialization:headerParams];
formParams = [sanitizer sanitizeForSerialization:formParams];
if(![body isKindOfClass:[NSData class]]) {
body = [self.sanitizer sanitizeForSerialization:body];
body = [sanitizer sanitizeForSerialization:body];
}
// auth setting
@ -279,22 +178,19 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
[resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString];
}];
NSMutableURLRequest * request = nil;
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams];
if ([pathWithQueryParams hasPrefix:@"/"]) {
pathWithQueryParams = [pathWithQueryParams substringFromIndex:1];
}
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
NSError *requestCreateError = nil;
NSMutableURLRequest * request = nil;
if (files.count > 0) {
__weak __typeof(self)weakSelf = self;
request = [self.requestSerializer multipartFormRequestWithMethod:@"POST"
URLString:urlString
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSString *objString = [weakSelf.sanitizer parameterToString:obj];
NSString *objString = [sanitizer parameterToString:obj];
NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:data name:key];
}];
@ -302,59 +198,43 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
NSURL *filePath = (NSURL *)obj;
[formData appendPartWithFileURL:filePath name:key error:nil];
}];
} error:nil];
} error:&requestCreateError];
}
else {
if (formParams) {
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:formParams
error:nil];
request = [requestSerializer requestWithMethod:method URLString:urlString parameters:formParams error:&requestCreateError];
}
if (body) {
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:body
error:nil];
request = [requestSerializer requestWithMethod:method URLString:urlString parameters:body error:&requestCreateError];
}
}
// request cache
BOOL hasHeaderParams = [headerParams count] > 0;
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(!request) {
completionBlock(nil, requestCreateError);
return nil;
}
if (hasHeaderParams){
if ([headerParams count] > 0){
for(NSString * key in [headerParams keyEnumerator]){
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
}
}
[self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
[requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
[self postProcessRequest:request];
NSURLSessionTask *task = nil;
if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) {
if ([self.downloadTaskResponseTypes containsObject:responseType]) {
task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
completionBlock(data, error);
}];
}
else {
} else {
__weak typeof(self) weakSelf = self;
task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
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){
error = serializationError;
}
@ -367,16 +247,24 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
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
-(void)postProcessRequest:(NSMutableURLRequest *)request {
// Always disable cookies!
[request setHTTPShouldHandleCookies:NO];
}
#pragma mark -
- (NSString*) pathWithQueryParamsToString:(NSString*) path
queryParams:(NSDictionary*) queryParams {
- (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams {
if(queryParams.count == 0) {
return path;
}
@ -434,9 +322,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
/**
* Update header and query params based on authentication settings
*/
- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers
queryParams:(NSDictionary *__autoreleasing *)querys
WithAuthSettings:(NSArray *)authSettings {
- (void) updateHeaderParams:(NSDictionary * *)headers queryParams:(NSDictionary * *)querys WithAuthSettings:(NSArray *)authSettings {
if ([authSettings count] == 0) {
return;
@ -466,7 +352,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
}
- (AFSecurityPolicy *) customSecurityPolicy {
- (AFSecurityPolicy *) createSecurityPolicy {
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
id<{{classPrefix}}Configuration> config = self.configuration;

View File

@ -17,78 +17,19 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration;
@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
@property(nonatomic, assign) NSTimeInterval timeoutInterval;
@property(nonatomic, readonly) NSOperationQueue* queue;
@property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer;
@property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer;
/**
* Clears Cache
*/
+(void)clearCache;
/**
* 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;
@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer <AFURLRequestSerialization> *>* requestSerializerForContentType;
/**
* Gets client singleton instance
*/
+ (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
@ -97,9 +38,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
* @param querys The query parameters will be updated, passed by pointer to pointer.
* @param authSettings The authentication names NSArray.
*/
- (void) updateHeaderParams:(NSDictionary **)headers
queryParams:(NSDictionary **)querys
WithAuthSettings:(NSArray *)authSettings;
- (void) updateHeaderParams:(NSDictionary **)headers queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings;
/**
@ -109,6 +48,14 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
*/
- (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
*
@ -139,11 +86,4 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
responseType: (NSString *) responseType
completionBlock: (void (^)(id, NSError *))completionBlock;
/**
* Custom security policy
*
* @return AFSecurityPolicy
*/
- (AFSecurityPolicy *) customSecurityPolicy;
@end

View File

@ -36,7 +36,7 @@
_mutableApiKey = [NSMutableDictionary dictionary];
_mutableApiKeyPrefix = [NSMutableDictionary dictionary];
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
{{#httpUserAgent}}_mutableDefaultHeaders[@"User-Agent"] = @"{{httpUserAgent}}"{{/httpUserAgent}};
{{#httpUserAgent}}_mutableDefaultHeaders[@"User-Agent"] = @"{{httpUserAgent}}";{{/httpUserAgent}}
_logger = [{{classPrefix}}Logger sharedLogger];
}
return self;
@ -144,8 +144,6 @@
self.logger.enabled = debug;
}
- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key {
if(!value) {
[self.mutableDefaultHeaders removeObjectForKey:key];

View File

@ -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

View File

@ -1,8 +0,0 @@
#import <Foundation/Foundation.h>
#import <AFNetworking/AFURLResponseSerialization.h>
{{>licenceInfo}}
@interface {{classPrefix}}JSONResponseSerializer : AFJSONResponseSerializer
@end

View File

@ -17,8 +17,7 @@
#pragma mark - Log Methods
- (void)debugLog:(NSString *)method
message:(NSString *)format, ... {
- (void)debugLog:(NSString *)method message:(NSString *)format, ... {
if (!self.isEnabled) {
return;
}

View File

@ -16,6 +16,7 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528;
@property (nonatomic, strong) NSNumberFormatter* numberFormatter;
@property (nonatomic, strong) NSArray *primitiveTypes;
@property (nonatomic, strong) NSArray *basicReturnTypes;
@property (nonatomic, strong) NSArray *dataReturnTypes;
@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression;
@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression;
@ -33,7 +34,9 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528;
formatter.numberStyle = NSNumberFormatterDecimalStyle;
_numberFormatter = formatter;
_primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"];
_basicReturnTypes = @[@"NSObject", @"id", @"NSData"];
_basicReturnTypes = @[@"NSObject", @"id"];
_dataReturnTypes = @[@"NSData"];
_arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>"
options:NSRegularExpressionCaseInsensitive
error:nil];
@ -53,23 +56,36 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528;
#pragma mark - Deserialize methods
- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error {
// return nil if data is nil or className is nil
if (!data || !className || [data isKindOfClass:[NSNull class]]) {
if (!data || !className) {
return nil;
}
// remove "*" from className, if ends with "*"
if ([className hasSuffix:@"*"]) {
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
if ([self.basicReturnTypes containsObject:className]) {
return data;
return jsonData;
}
// primitives
if ([self.primitiveTypes containsObject:className]) {
return [self deserializePrimitiveValue:data class:className error:error];
return [self deserializePrimitiveValue:jsonData class:className error:error];
}
NSTextCheckingResult *match = nil;
@ -78,37 +94,37 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528;
match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range];
if (match) {
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
match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range];
if (match) {
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
return [self deserializeArrayValue:data innerType:innerType error:error];
return [self deserializeArrayValue:jsonData innerType:innerType error:error];
}
// map
match = [self.dictPatExpression firstMatchInString:className options:0 range:range];
if (match) {
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];
if (match) {
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
return [self deserializeDictionaryValue:data valueType:valueType error:error];
return [self deserializeDictionaryValue:jsonData valueType:valueType error:error];
}
// model
Class ModelClass = NSClassFromString(className);
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error];
return [(JSONModel *) [ModelClass alloc] initWithDictionary:jsonData error:error];
}
if(error) {
*error = [self unknownResponseErrorWithExpectedType:className data:data];
*error = [self unknownResponseErrorWithExpectedType:className data:jsonData];
}
return nil;
}
@ -172,7 +188,7 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528;
- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error {
if ([className isEqualToString:@"NSString"]) {
return [NSString stringWithString:data];
return [NSString stringWithFormat:@"%@",data];
}
else if ([className isEqualToString:@"NSDate"]) {
return [self deserializeDateValue:data error:error];

View File

@ -3,6 +3,8 @@
#import "{{classPrefix}}QueryParamCollection.h"
#import <ISO8601/ISO8601.h>
NSString * const k{{classPrefix}}ApplicationJSONType = @"application/json";
NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) {
static NSString * const k{{classPrefix}}CharactersGeneralDelimitersToEncode = @":#[]@";
static NSString * const k{{classPrefix}}CharactersSubDelimitersToEncode = @"!$&'()*+,;=";
@ -43,8 +45,6 @@ NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) {
@implementation {{classPrefix}}Sanitizer
static NSString * kApplicationJSONType = @"application/json";
-(instancetype)init {
self = [super init];
if ( !self ) {
@ -141,7 +141,7 @@ static NSString * kApplicationJSONType = @"application/json";
NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]];
for (NSString *string in accepts) {
if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) {
return kApplicationJSONType;
return k{{classPrefix}}ApplicationJSONType;
}
[lowerAccepts addObject:[string lowercaseString]];
}
@ -153,12 +153,12 @@ static NSString * kApplicationJSONType = @"application/json";
*/
- (NSString *) selectHeaderContentType:(NSArray *)contentTypes {
if (contentTypes.count == 0) {
return kApplicationJSONType;
return k{{classPrefix}}ApplicationJSONType;
}
NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]];
for (NSString *string in contentTypes) {
if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){
return kApplicationJSONType;
return k{{classPrefix}}ApplicationJSONType;
}
[lowerContentTypes addObject:[string lowercaseString]];
}

View File

@ -4,6 +4,8 @@
extern NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string);
extern NSString * const k{{classPrefix}}ApplicationJSONType;
@protocol {{classPrefix}}Sanitizer <NSObject>
/**

View File

@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi
- API version: 1.0.0
- 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
## Requirements

View File

@ -39,78 +39,19 @@ extern NSString *const SWGResponseObjectErrorKey;
@property (nonatomic, strong, readonly) id<SWGConfiguration> configuration;
@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
@property(nonatomic, assign) NSTimeInterval timeoutInterval;
@property(nonatomic, readonly) NSOperationQueue* queue;
@property(nonatomic, strong) id<SWGResponseDeserializer> responseDeserializer;
@property(nonatomic, strong) id<SWGSanitizer> sanitizer;
/**
* Clears Cache
*/
+(void)clearCache;
/**
* 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;
@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer <AFURLRequestSerialization> *>* requestSerializerForContentType;
/**
* Gets client singleton instance
*/
+ (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
@ -119,9 +60,7 @@ extern NSString *const SWGResponseObjectErrorKey;
* @param querys The query parameters will be updated, passed by pointer to pointer.
* @param authSettings The authentication names NSArray.
*/
- (void) updateHeaderParams:(NSDictionary **)headers
queryParams:(NSDictionary **)querys
WithAuthSettings:(NSArray *)authSettings;
- (void) updateHeaderParams:(NSDictionary **)headers queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings;
/**
@ -131,6 +70,14 @@ extern NSString *const SWGResponseObjectErrorKey;
*/
- (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
*
@ -161,11 +108,4 @@ extern NSString *const SWGResponseObjectErrorKey;
responseType: (NSString *) responseType
completionBlock: (void (^)(id, NSError *))completionBlock;
/**
* Custom security policy
*
* @return AFSecurityPolicy
*/
- (AFSecurityPolicy *) customSecurityPolicy;
@end

View File

@ -1,21 +1,13 @@
#import <ISO8601/NSDate+ISO8601.h>
#import "SWGLogger.h"
#import "SWGApiClient.h"
#import "SWGJSONRequestSerializer.h"
#import "SWGJSONResponseSerializer.h"
#import "SWGQueryParamCollection.h"
#import "SWGDefaultConfiguration.h"
NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject";
static bool offlineState = false;
static bool cacheEnabled = false;
static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable;
static void (^reachabilityChangeBlock)(int);
static NSString * const kSWGContentDispositionKey = @"Content-Disposition";
static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) {
if(![response isKindOfClass:[NSHTTPURLResponse class]]) {
@ -26,17 +18,13 @@ static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) {
static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
NSDictionary * headers = SWG__headerFieldsForResponse(response);
if(!headers[@"Content-Disposition"]) {
if(!headers[kSWGContentDispositionKey]) {
return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
}
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?";
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *contentDispositionHeader = headers[@"Content-Disposition"];
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader
options:0
range:NSMakeRange(0, [contentDispositionHeader length])];
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
NSString *contentDispositionHeader = headers[kSWGContentDispositionKey];
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader options:0 range:NSMakeRange(0, [contentDispositionHeader length])];
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) NSArray<NSString*>* downloadTaskResponseTypes;
@end
@implementation SWGApiClient
@ -75,7 +65,6 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
}
- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<SWGConfiguration>)configuration {
self = [super initWithBaseURL:url];
if (self) {
_configuration = configuration;
@ -83,102 +72,30 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
_responseDeserializer = [[SWGResponseDeserializer alloc] init];
_sanitizer = [[SWGSanitizer alloc] init];
self.requestSerializer = [AFJSONRequestSerializer serializer];
self.responseSerializer = [AFJSONResponseSerializer serializer];
self.securityPolicy = [self customSecurityPolicy];
_downloadTaskResponseTypes = @[@"NSURL*", @"NSURL"];
// configure reachability
[self configureCacheReachibility];
AFHTTPRequestSerializer* afhttpRequestSerializer = [AFHTTPRequestSerializer serializer];
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;
}
#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
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request
completionBlock: (void (^)(id, NSError *))completionBlock {
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock {
NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
SWGDebugLogResponse(response, responseObject,request,error);
if(!error) {
completionBlock(responseObject, nil);
return;
}
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
if (responseObject) {
// Add in the (parsed) response body.
@ -191,10 +108,9 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
return task;
}
- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request
completionBlock: (void (^)(id, NSError *))completionBlock {
id<SWGConfiguration> config = self.configuration;
- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock {
__block NSString * tempFolderPath = [self.configuration.tempFolderPath copy];
NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *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];
completionBlock(nil, augmentedError);
return;
}
NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory();
NSString *directory = tempFolderPath ?: NSTemporaryDirectory();
NSString *filename = SWG__fileNameForResponse(response);
NSString *filepath = [directory stringByAppendingPathComponent:filename];
@ -238,35 +155,17 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
responseType: (NSString *) responseType
completionBlock: (void (^)(id, NSError *))completionBlock {
// setting request serializer
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);
}
AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer = [self requestSerializerForRequestContentType:requestContentType];
// setting response serializer
if ([responseContentType isEqualToString:@"application/json"]) {
self.responseSerializer = [SWGJSONResponseSerializer serializer];
} else {
self.responseSerializer = [AFHTTPResponseSerializer serializer];
}
__weak id<SWGSanitizer> sanitizer = self.sanitizer;
// sanitize parameters
pathParams = [self.sanitizer sanitizeForSerialization:pathParams];
queryParams = [self.sanitizer sanitizeForSerialization:queryParams];
headerParams = [self.sanitizer sanitizeForSerialization:headerParams];
formParams = [self.sanitizer sanitizeForSerialization:formParams];
pathParams = [sanitizer sanitizeForSerialization:pathParams];
queryParams = [sanitizer sanitizeForSerialization:queryParams];
headerParams = [sanitizer sanitizeForSerialization:headerParams];
formParams = [sanitizer sanitizeForSerialization:formParams];
if(![body isKindOfClass:[NSData class]]) {
body = [self.sanitizer sanitizeForSerialization:body];
body = [sanitizer sanitizeForSerialization:body];
}
// auth setting
@ -279,22 +178,19 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
[resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString];
}];
NSMutableURLRequest * request = nil;
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams];
if ([pathWithQueryParams hasPrefix:@"/"]) {
pathWithQueryParams = [pathWithQueryParams substringFromIndex:1];
}
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
NSError *requestCreateError = nil;
NSMutableURLRequest * request = nil;
if (files.count > 0) {
__weak __typeof(self)weakSelf = self;
request = [self.requestSerializer multipartFormRequestWithMethod:@"POST"
URLString:urlString
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSString *objString = [weakSelf.sanitizer parameterToString:obj];
NSString *objString = [sanitizer parameterToString:obj];
NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:data name:key];
}];
@ -302,59 +198,43 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
NSURL *filePath = (NSURL *)obj;
[formData appendPartWithFileURL:filePath name:key error:nil];
}];
} error:nil];
} error:&requestCreateError];
}
else {
if (formParams) {
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:formParams
error:nil];
request = [requestSerializer requestWithMethod:method URLString:urlString parameters:formParams error:&requestCreateError];
}
if (body) {
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:body
error:nil];
request = [requestSerializer requestWithMethod:method URLString:urlString parameters:body error:&requestCreateError];
}
}
// request cache
BOOL hasHeaderParams = [headerParams count] > 0;
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(!request) {
completionBlock(nil, requestCreateError);
return nil;
}
if (hasHeaderParams){
if ([headerParams count] > 0){
for(NSString * key in [headerParams keyEnumerator]){
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
}
}
[self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
[requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
[self postProcessRequest:request];
NSURLSessionTask *task = nil;
if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) {
if ([self.downloadTaskResponseTypes containsObject:responseType]) {
task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
completionBlock(data, error);
}];
}
else {
} else {
__weak typeof(self) weakSelf = self;
task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
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){
error = serializationError;
}
@ -367,16 +247,24 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
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
-(void)postProcessRequest:(NSMutableURLRequest *)request {
// Always disable cookies!
[request setHTTPShouldHandleCookies:NO];
}
#pragma mark -
- (NSString*) pathWithQueryParamsToString:(NSString*) path
queryParams:(NSDictionary*) queryParams {
- (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams {
if(queryParams.count == 0) {
return path;
}
@ -434,9 +322,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
/**
* Update header and query params based on authentication settings
*/
- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers
queryParams:(NSDictionary *__autoreleasing *)querys
WithAuthSettings:(NSArray *)authSettings {
- (void) updateHeaderParams:(NSDictionary * *)headers queryParams:(NSDictionary * *)querys WithAuthSettings:(NSArray *)authSettings {
if ([authSettings count] == 0) {
return;
@ -466,7 +352,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
}
- (AFSecurityPolicy *) customSecurityPolicy {
- (AFSecurityPolicy *) createSecurityPolicy {
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
id<SWGConfiguration> config = self.configuration;

View File

@ -36,7 +36,7 @@
_mutableApiKey = [NSMutableDictionary dictionary];
_mutableApiKeyPrefix = [NSMutableDictionary dictionary];
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
;
_logger = [SWGLogger sharedLogger];
}
return self;
@ -129,8 +129,6 @@
self.logger.enabled = debug;
}
- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key {
if(!value) {
[self.mutableDefaultHeaders removeObjectForKey:key];

View File

@ -17,8 +17,7 @@
#pragma mark - Log Methods
- (void)debugLog:(NSString *)method
message:(NSString *)format, ... {
- (void)debugLog:(NSString *)method message:(NSString *)format, ... {
if (!self.isEnabled) {
return;
}

View File

@ -16,6 +16,7 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
@property (nonatomic, strong) NSNumberFormatter* numberFormatter;
@property (nonatomic, strong) NSArray *primitiveTypes;
@property (nonatomic, strong) NSArray *basicReturnTypes;
@property (nonatomic, strong) NSArray *dataReturnTypes;
@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression;
@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression;
@ -33,7 +34,9 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
formatter.numberStyle = NSNumberFormatterDecimalStyle;
_numberFormatter = formatter;
_primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"];
_basicReturnTypes = @[@"NSObject", @"id", @"NSData"];
_basicReturnTypes = @[@"NSObject", @"id"];
_dataReturnTypes = @[@"NSData"];
_arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>"
options:NSRegularExpressionCaseInsensitive
error:nil];
@ -53,23 +56,36 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
#pragma mark - Deserialize methods
- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error {
// return nil if data is nil or className is nil
if (!data || !className || [data isKindOfClass:[NSNull class]]) {
if (!data || !className) {
return nil;
}
// remove "*" from className, if ends with "*"
if ([className hasSuffix:@"*"]) {
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
if ([self.basicReturnTypes containsObject:className]) {
return data;
return jsonData;
}
// primitives
if ([self.primitiveTypes containsObject:className]) {
return [self deserializePrimitiveValue:data class:className error:error];
return [self deserializePrimitiveValue:jsonData class:className error:error];
}
NSTextCheckingResult *match = nil;
@ -78,37 +94,37 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range];
if (match) {
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
match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range];
if (match) {
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
return [self deserializeArrayValue:data innerType:innerType error:error];
return [self deserializeArrayValue:jsonData innerType:innerType error:error];
}
// map
match = [self.dictPatExpression firstMatchInString:className options:0 range:range];
if (match) {
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];
if (match) {
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
return [self deserializeDictionaryValue:data valueType:valueType error:error];
return [self deserializeDictionaryValue:jsonData valueType:valueType error:error];
}
// model
Class ModelClass = NSClassFromString(className);
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error];
return [(JSONModel *) [ModelClass alloc] initWithDictionary:jsonData error:error];
}
if(error) {
*error = [self unknownResponseErrorWithExpectedType:className data:data];
*error = [self unknownResponseErrorWithExpectedType:className data:jsonData];
}
return nil;
}
@ -172,7 +188,7 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error {
if ([className isEqualToString:@"NSString"]) {
return [NSString stringWithString:data];
return [NSString stringWithFormat:@"%@",data];
}
else if ([className isEqualToString:@"NSDate"]) {
return [self deserializeDateValue:data error:error];

View File

@ -26,6 +26,8 @@
extern NSString * SWGPercentEscapedStringFromString(NSString *string);
extern NSString * const kSWGApplicationJSONType;
@protocol SWGSanitizer <NSObject>
/**

View File

@ -3,6 +3,8 @@
#import "SWGQueryParamCollection.h"
#import <ISO8601/ISO8601.h>
NSString * const kSWGApplicationJSONType = @"application/json";
NSString * SWGPercentEscapedStringFromString(NSString *string) {
static NSString * const kSWGCharactersGeneralDelimitersToEncode = @":#[]@";
static NSString * const kSWGCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
@ -43,8 +45,6 @@ NSString * SWGPercentEscapedStringFromString(NSString *string) {
@implementation SWGSanitizer
static NSString * kApplicationJSONType = @"application/json";
-(instancetype)init {
self = [super init];
if ( !self ) {
@ -141,7 +141,7 @@ static NSString * kApplicationJSONType = @"application/json";
NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]];
for (NSString *string in accepts) {
if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) {
return kApplicationJSONType;
return kSWGApplicationJSONType;
}
[lowerAccepts addObject:[string lowercaseString]];
}
@ -153,12 +153,12 @@ static NSString * kApplicationJSONType = @"application/json";
*/
- (NSString *) selectHeaderContentType:(NSArray *)contentTypes {
if (contentTypes.count == 0) {
return kApplicationJSONType;
return kSWGApplicationJSONType;
}
NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]];
for (NSString *string in contentTypes) {
if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){
return kApplicationJSONType;
return kSWGApplicationJSONType;
}
[lowerContentTypes addObject:[string lowercaseString]];
}

View File

@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi
- API version: 1.0.0
- 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
## Requirements

View File

@ -39,78 +39,19 @@ extern NSString *const SWGResponseObjectErrorKey;
@property (nonatomic, strong, readonly) id<SWGConfiguration> configuration;
@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
@property(nonatomic, assign) NSTimeInterval timeoutInterval;
@property(nonatomic, readonly) NSOperationQueue* queue;
@property(nonatomic, strong) id<SWGResponseDeserializer> responseDeserializer;
@property(nonatomic, strong) id<SWGSanitizer> sanitizer;
/**
* Clears Cache
*/
+(void)clearCache;
/**
* 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;
@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer <AFURLRequestSerialization> *>* requestSerializerForContentType;
/**
* Gets client singleton instance
*/
+ (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
@ -119,9 +60,7 @@ extern NSString *const SWGResponseObjectErrorKey;
* @param querys The query parameters will be updated, passed by pointer to pointer.
* @param authSettings The authentication names NSArray.
*/
- (void) updateHeaderParams:(NSDictionary **)headers
queryParams:(NSDictionary **)querys
WithAuthSettings:(NSArray *)authSettings;
- (void) updateHeaderParams:(NSDictionary **)headers queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings;
/**
@ -131,6 +70,14 @@ extern NSString *const SWGResponseObjectErrorKey;
*/
- (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
*
@ -161,11 +108,4 @@ extern NSString *const SWGResponseObjectErrorKey;
responseType: (NSString *) responseType
completionBlock: (void (^)(id, NSError *))completionBlock;
/**
* Custom security policy
*
* @return AFSecurityPolicy
*/
- (AFSecurityPolicy *) customSecurityPolicy;
@end

View File

@ -1,21 +1,13 @@
#import <ISO8601/NSDate+ISO8601.h>
#import "SWGLogger.h"
#import "SWGApiClient.h"
#import "SWGJSONRequestSerializer.h"
#import "SWGJSONResponseSerializer.h"
#import "SWGQueryParamCollection.h"
#import "SWGDefaultConfiguration.h"
NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject";
static bool offlineState = false;
static bool cacheEnabled = false;
static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable;
static void (^reachabilityChangeBlock)(int);
static NSString * const kSWGContentDispositionKey = @"Content-Disposition";
static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) {
if(![response isKindOfClass:[NSHTTPURLResponse class]]) {
@ -26,17 +18,13 @@ static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) {
static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
NSDictionary * headers = SWG__headerFieldsForResponse(response);
if(!headers[@"Content-Disposition"]) {
if(!headers[kSWGContentDispositionKey]) {
return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
}
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?";
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *contentDispositionHeader = headers[@"Content-Disposition"];
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader
options:0
range:NSMakeRange(0, [contentDispositionHeader length])];
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
NSString *contentDispositionHeader = headers[kSWGContentDispositionKey];
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader options:0 range:NSMakeRange(0, [contentDispositionHeader length])];
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) NSArray<NSString*>* downloadTaskResponseTypes;
@end
@implementation SWGApiClient
@ -75,7 +65,6 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
}
- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<SWGConfiguration>)configuration {
self = [super initWithBaseURL:url];
if (self) {
_configuration = configuration;
@ -83,102 +72,30 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
_responseDeserializer = [[SWGResponseDeserializer alloc] init];
_sanitizer = [[SWGSanitizer alloc] init];
self.requestSerializer = [AFJSONRequestSerializer serializer];
self.responseSerializer = [AFJSONResponseSerializer serializer];
self.securityPolicy = [self customSecurityPolicy];
_downloadTaskResponseTypes = @[@"NSURL*", @"NSURL"];
// configure reachability
[self configureCacheReachibility];
AFHTTPRequestSerializer* afhttpRequestSerializer = [AFHTTPRequestSerializer serializer];
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;
}
#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
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request
completionBlock: (void (^)(id, NSError *))completionBlock {
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock {
NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
SWGDebugLogResponse(response, responseObject,request,error);
if(!error) {
completionBlock(responseObject, nil);
return;
}
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
if (responseObject) {
// Add in the (parsed) response body.
@ -191,10 +108,9 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
return task;
}
- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request
completionBlock: (void (^)(id, NSError *))completionBlock {
id<SWGConfiguration> config = self.configuration;
- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock {
__block NSString * tempFolderPath = [self.configuration.tempFolderPath copy];
NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *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];
completionBlock(nil, augmentedError);
return;
}
NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory();
NSString *directory = tempFolderPath ?: NSTemporaryDirectory();
NSString *filename = SWG__fileNameForResponse(response);
NSString *filepath = [directory stringByAppendingPathComponent:filename];
@ -238,35 +155,17 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
responseType: (NSString *) responseType
completionBlock: (void (^)(id, NSError *))completionBlock {
// setting request serializer
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);
}
AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer = [self requestSerializerForRequestContentType:requestContentType];
// setting response serializer
if ([responseContentType isEqualToString:@"application/json"]) {
self.responseSerializer = [SWGJSONResponseSerializer serializer];
} else {
self.responseSerializer = [AFHTTPResponseSerializer serializer];
}
__weak id<SWGSanitizer> sanitizer = self.sanitizer;
// sanitize parameters
pathParams = [self.sanitizer sanitizeForSerialization:pathParams];
queryParams = [self.sanitizer sanitizeForSerialization:queryParams];
headerParams = [self.sanitizer sanitizeForSerialization:headerParams];
formParams = [self.sanitizer sanitizeForSerialization:formParams];
pathParams = [sanitizer sanitizeForSerialization:pathParams];
queryParams = [sanitizer sanitizeForSerialization:queryParams];
headerParams = [sanitizer sanitizeForSerialization:headerParams];
formParams = [sanitizer sanitizeForSerialization:formParams];
if(![body isKindOfClass:[NSData class]]) {
body = [self.sanitizer sanitizeForSerialization:body];
body = [sanitizer sanitizeForSerialization:body];
}
// auth setting
@ -279,22 +178,19 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
[resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString];
}];
NSMutableURLRequest * request = nil;
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams];
if ([pathWithQueryParams hasPrefix:@"/"]) {
pathWithQueryParams = [pathWithQueryParams substringFromIndex:1];
}
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
NSError *requestCreateError = nil;
NSMutableURLRequest * request = nil;
if (files.count > 0) {
__weak __typeof(self)weakSelf = self;
request = [self.requestSerializer multipartFormRequestWithMethod:@"POST"
URLString:urlString
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSString *objString = [weakSelf.sanitizer parameterToString:obj];
NSString *objString = [sanitizer parameterToString:obj];
NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:data name:key];
}];
@ -302,59 +198,43 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
NSURL *filePath = (NSURL *)obj;
[formData appendPartWithFileURL:filePath name:key error:nil];
}];
} error:nil];
} error:&requestCreateError];
}
else {
if (formParams) {
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:formParams
error:nil];
request = [requestSerializer requestWithMethod:method URLString:urlString parameters:formParams error:&requestCreateError];
}
if (body) {
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:body
error:nil];
request = [requestSerializer requestWithMethod:method URLString:urlString parameters:body error:&requestCreateError];
}
}
// request cache
BOOL hasHeaderParams = [headerParams count] > 0;
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(!request) {
completionBlock(nil, requestCreateError);
return nil;
}
if (hasHeaderParams){
if ([headerParams count] > 0){
for(NSString * key in [headerParams keyEnumerator]){
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
}
}
[self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
[requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
[self postProcessRequest:request];
NSURLSessionTask *task = nil;
if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) {
if ([self.downloadTaskResponseTypes containsObject:responseType]) {
task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
completionBlock(data, error);
}];
}
else {
} else {
__weak typeof(self) weakSelf = self;
task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
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){
error = serializationError;
}
@ -367,16 +247,24 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
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
-(void)postProcessRequest:(NSMutableURLRequest *)request {
// Always disable cookies!
[request setHTTPShouldHandleCookies:NO];
}
#pragma mark -
- (NSString*) pathWithQueryParamsToString:(NSString*) path
queryParams:(NSDictionary*) queryParams {
- (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams {
if(queryParams.count == 0) {
return path;
}
@ -434,9 +322,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
/**
* Update header and query params based on authentication settings
*/
- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers
queryParams:(NSDictionary *__autoreleasing *)querys
WithAuthSettings:(NSArray *)authSettings {
- (void) updateHeaderParams:(NSDictionary * *)headers queryParams:(NSDictionary * *)querys WithAuthSettings:(NSArray *)authSettings {
if ([authSettings count] == 0) {
return;
@ -466,7 +352,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
}
- (AFSecurityPolicy *) customSecurityPolicy {
- (AFSecurityPolicy *) createSecurityPolicy {
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
id<SWGConfiguration> config = self.configuration;

View File

@ -36,7 +36,7 @@
_mutableApiKey = [NSMutableDictionary dictionary];
_mutableApiKeyPrefix = [NSMutableDictionary dictionary];
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
;
_logger = [SWGLogger sharedLogger];
}
return self;
@ -129,8 +129,6 @@
self.logger.enabled = debug;
}
- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key {
if(!value) {
[self.mutableDefaultHeaders removeObjectForKey:key];

View File

@ -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

View File

@ -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

View File

@ -17,8 +17,7 @@
#pragma mark - Log Methods
- (void)debugLog:(NSString *)method
message:(NSString *)format, ... {
- (void)debugLog:(NSString *)method message:(NSString *)format, ... {
if (!self.isEnabled) {
return;
}

View File

@ -16,6 +16,7 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
@property (nonatomic, strong) NSNumberFormatter* numberFormatter;
@property (nonatomic, strong) NSArray *primitiveTypes;
@property (nonatomic, strong) NSArray *basicReturnTypes;
@property (nonatomic, strong) NSArray *dataReturnTypes;
@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression;
@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression;
@ -33,7 +34,9 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
formatter.numberStyle = NSNumberFormatterDecimalStyle;
_numberFormatter = formatter;
_primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"];
_basicReturnTypes = @[@"NSObject", @"id", @"NSData"];
_basicReturnTypes = @[@"NSObject", @"id"];
_dataReturnTypes = @[@"NSData"];
_arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>"
options:NSRegularExpressionCaseInsensitive
error:nil];
@ -53,23 +56,36 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
#pragma mark - Deserialize methods
- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error {
// return nil if data is nil or className is nil
if (!data || !className || [data isKindOfClass:[NSNull class]]) {
if (!data || !className) {
return nil;
}
// remove "*" from className, if ends with "*"
if ([className hasSuffix:@"*"]) {
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
if ([self.basicReturnTypes containsObject:className]) {
return data;
return jsonData;
}
// primitives
if ([self.primitiveTypes containsObject:className]) {
return [self deserializePrimitiveValue:data class:className error:error];
return [self deserializePrimitiveValue:jsonData class:className error:error];
}
NSTextCheckingResult *match = nil;
@ -78,37 +94,37 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range];
if (match) {
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
match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range];
if (match) {
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
return [self deserializeArrayValue:data innerType:innerType error:error];
return [self deserializeArrayValue:jsonData innerType:innerType error:error];
}
// map
match = [self.dictPatExpression firstMatchInString:className options:0 range:range];
if (match) {
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];
if (match) {
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
return [self deserializeDictionaryValue:data valueType:valueType error:error];
return [self deserializeDictionaryValue:jsonData valueType:valueType error:error];
}
// model
Class ModelClass = NSClassFromString(className);
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error];
return [(JSONModel *) [ModelClass alloc] initWithDictionary:jsonData error:error];
}
if(error) {
*error = [self unknownResponseErrorWithExpectedType:className data:data];
*error = [self unknownResponseErrorWithExpectedType:className data:jsonData];
}
return nil;
}
@ -172,7 +188,7 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error {
if ([className isEqualToString:@"NSString"]) {
return [NSString stringWithString:data];
return [NSString stringWithFormat:@"%@",data];
}
else if ([className isEqualToString:@"NSDate"]) {
return [self deserializeDateValue:data error:error];

View File

@ -26,6 +26,8 @@
extern NSString * SWGPercentEscapedStringFromString(NSString *string);
extern NSString * const kSWGApplicationJSONType;
@protocol SWGSanitizer <NSObject>
/**

View File

@ -3,6 +3,8 @@
#import "SWGQueryParamCollection.h"
#import <ISO8601/ISO8601.h>
NSString * const kSWGApplicationJSONType = @"application/json";
NSString * SWGPercentEscapedStringFromString(NSString *string) {
static NSString * const kSWGCharactersGeneralDelimitersToEncode = @":#[]@";
static NSString * const kSWGCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
@ -43,8 +45,6 @@ NSString * SWGPercentEscapedStringFromString(NSString *string) {
@implementation SWGSanitizer
static NSString * kApplicationJSONType = @"application/json";
-(instancetype)init {
self = [super init];
if ( !self ) {
@ -141,7 +141,7 @@ static NSString * kApplicationJSONType = @"application/json";
NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]];
for (NSString *string in accepts) {
if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) {
return kApplicationJSONType;
return kSWGApplicationJSONType;
}
[lowerAccepts addObject:[string lowercaseString]];
}
@ -153,12 +153,12 @@ static NSString * kApplicationJSONType = @"application/json";
*/
- (NSString *) selectHeaderContentType:(NSArray *)contentTypes {
if (contentTypes.count == 0) {
return kApplicationJSONType;
return kSWGApplicationJSONType;
}
NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]];
for (NSString *string in contentTypes) {
if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){
return kApplicationJSONType;
return kSWGApplicationJSONType;
}
[lowerContentTypes addObject:[string lowercaseString]];
}

View File

@ -250,4 +250,16 @@
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

View File

@ -30,14 +30,7 @@
if (!output) {
XCTFail(@"response can't be nil");
}
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);
XCTAssertTrue([output rangeOfString:@"logged in user"].location != NSNotFound);
[expectation fulfill];
}];