diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index 60df478db4a..d8b20ae5dd0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -245,8 +245,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m")); 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("ApiSessionManager-header.mustache", coreFileFolder(), classPrefix + "ApiSessionManager.h")); - supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", coreFileFolder(), classPrefix + "ApiSessionManager.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("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); @@ -259,11 +259,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h")); - supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", coreFileFolder(), classPrefix + "Configuration.h")); - supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.m")); - supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.h")); - supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.h")); - supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.m")); + supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m")); + supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h")); supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h")); supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache similarity index 76% rename from modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-body.mustache rename to modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index 6b454063ada..10cb6528d86 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -1,16 +1,10 @@ -#import - -#import "{{classPrefix}}ApiSessionManager.h" -#import "{{classPrefix}}JSONRequestSerializer.h" -#import "{{classPrefix}}JSONResponseSerializer.h" -#import "{{classPrefix}}QueryParamCollection.h" -#import "{{classPrefix}}DefaultConfiguration.h" - - +#import "{{classPrefix}}ApiClient.h" NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; +static NSUInteger requestId = 0; static bool offlineState = false; +static NSMutableSet * queuedRequests = nil; static bool cacheEnabled = false; static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; static void (^reachabilityChangeBlock)(int); @@ -40,52 +34,42 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) } -@interface {{classPrefix}}ApiSessionManager () +@interface {{classPrefix}}ApiClient () -@property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration; +@property (nonatomic, strong) NSDictionary* HTTPResponseHeaders; @end -@implementation {{classPrefix}}ApiSessionManager +@implementation {{classPrefix}}ApiClient - (instancetype)init { - - return [self initWithConfiguration:[{{classPrefix}}DefaultConfiguration sharedConfig]]; + NSString *baseUrl = [[{{classPrefix}}Configuration sharedConfig] host]; + return [self initWithBaseURL:[NSURL URLWithString:baseUrl]]; } - (instancetype)initWithBaseURL:(NSURL *)url { - - return [self initWithBaseURL:url - configuration:[{{classPrefix}}DefaultConfiguration sharedConfig]]; - -} - -- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration { - - return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration]; -} - -- (instancetype)initWithBaseURL:(NSURL *)url - configuration:(id<{{classPrefix}}Configuration>)configuration { - self = [super initWithBaseURL:url]; if (self) { - _configuration = configuration; - _timeoutInterval = 60; - _responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init]; - _sanitizer = [[{{classPrefix}}Sanitizer alloc] init]; - + self.timeoutInterval = 60; self.requestSerializer = [AFJSONRequestSerializer serializer]; self.responseSerializer = [AFJSONResponseSerializer serializer]; self.securityPolicy = [self customSecurityPolicy]; - + self.responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init]; + self.sanitizer = [[{{classPrefix}}Sanitizer alloc] init]; // configure reachability [self configureCacheReachibility]; } - return self; } ++ (void)initialize { + if (self == [{{classPrefix}}ApiClient class]) { + queuedRequests = [[NSMutableSet alloc] init]; + // initialize URL cache + [self configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024]; + } +} + #pragma mark - Setter Methods + (void) setOfflineState:(BOOL) state { @@ -129,6 +113,43 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [NSURLCache setSharedURLCache:cache]; } +#pragma mark - Request Methods + ++(NSUInteger)requestQueueSize { + return [queuedRequests count]; +} + ++(NSNumber*) nextRequestId { + @synchronized(self) { + return @(++requestId); + } +} + ++(NSNumber*) queueRequest { + NSNumber* requestId = [[self class] nextRequestId]; + {{classPrefix}}DebugLog(@"added %@ to request queue", requestId); + [queuedRequests addObject:requestId]; + return requestId; +} + ++(void) cancelRequest:(NSNumber*)requestId { + [queuedRequests removeObject:requestId]; +} + +-(Boolean) executeRequestWithId:(NSNumber*) requestId { + NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { + return [obj intValue] == [requestId intValue]; + }]; + + if (matchingItems.count == 1) { + {{classPrefix}}DebugLog(@"removed request id %@", requestId); + [queuedRequests removeObject:requestId]; + return YES; + } else { + return NO; + } +} + #pragma mark - Reachability Methods +(AFNetworkReachabilityStatus) getReachabilityStatus { @@ -147,7 +168,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { reachabilityStatus = status; {{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); - [{{classPrefix}}ApiSessionManager setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; + [{{classPrefix}}ApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; // call the reachability block, if configured if (reachabilityChangeBlock != nil) { @@ -158,19 +179,23 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [self.reachabilityManager startMonitoring]; } -#pragma mark - Task Methods +#pragma mark - Operation Methods -- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request - completionBlock: (void (^)(id, NSError *))completionBlock { - - NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { +- (void) operationWithCompletionBlock: (NSURLRequest *)request + requestId: (NSNumber *) requestId + completionBlock: (void (^)(id, NSError *))completionBlock { + __weak __typeof(self)weakSelf = self; + NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if (![strongSelf executeRequestWithId:requestId]) { + return; + } {{classPrefix}}DebugLogResponse(response, responseObject,request,error); - + strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); if(!error) { completionBlock(responseObject, nil); return; } - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; if (responseObject) { // Add in the (parsed) response body. @@ -179,18 +204,20 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; completionBlock(nil, augmentedError); }]; - - return task; + [op resume]; } -- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request - completionBlock: (void (^)(id, NSError *))completionBlock { - - id<{{classPrefix}}Configuration> config = self.configuration; - - NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { +- (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request + requestId: (NSNumber *) requestId + completionBlock: (void (^)(id, NSError *))completionBlock { + __weak __typeof(self)weakSelf = self; + NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if (![strongSelf executeRequestWithId:requestId]) { + return; + } + strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); {{classPrefix}}DebugLogResponse(response, responseObject,request,error); - if(error) { NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; if (responseObject) { @@ -199,9 +226,8 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; completionBlock(nil, augmentedError); } - - NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory(); - NSString *filename = {{classPrefix}}__fileNameForResponse(response); + NSString *directory = [self configuration].tempFolderPath ?: NSTemporaryDirectory(); + NSString * filename = {{classPrefix}}__fileNameForResponse(response); NSString *filepath = [directory stringByAppendingPathComponent:filename]; NSURL *file = [NSURL fileURLWithPath:filepath]; @@ -210,26 +236,24 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) completionBlock(file, nil); }]; - - return task; + [op resume]; } -#pragma mark - Perform Request Methods - -- (NSURLSessionTask*) requestWithPath: (NSString*) path - method: (NSString*) method - pathParams: (NSDictionary *) pathParams - queryParams: (NSDictionary*) queryParams - formParams: (NSDictionary *) formParams - files: (NSDictionary *) files - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - responseType: (NSString *) responseType - completionBlock: (void (^)(id, NSError *))completionBlock { +#pragma mark - Perform Request Methods +-(NSNumber*) requestWithPath: (NSString*) path + method: (NSString*) method + pathParams: (NSDictionary *) pathParams + queryParams: (NSDictionary*) queryParams + formParams: (NSDictionary *) formParams + files: (NSDictionary *) files + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + responseType: (NSString *) responseType + completionBlock: (void (^)(id, NSError *))completionBlock { // setting request serializer if ([requestContentType isEqualToString:@"application/json"]) { self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer]; @@ -335,16 +359,14 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [self postProcessRequest:request]; - - NSURLSessionTask *task = nil; - + NSNumber* requestId = [{{classPrefix}}ApiClient queueRequest]; if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { - task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { + [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { completionBlock(data, error); }]; } else { - task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { + [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { NSError * serializationError; id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; if(!response && !error){ @@ -353,10 +375,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) completionBlock(response, error); }]; } - - [task resume]; - - return task; + return requestId; } //Added for easier override to modify request @@ -436,11 +455,10 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; - - id<{{classPrefix}}Configuration> config = self.configuration; - for (NSString *auth in authSettings) { - NSDictionary *authSetting = config.authSettings[auth]; + NSDictionary* configurationAuthSettings = [[self configuration] authSettings]; + for (NSString *auth in authSettings) { + NSDictionary *authSetting = configurationAuthSettings[auth]; if(!authSetting) { // auth setting is set only if the key is non-empty continue; } @@ -461,11 +479,11 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) - (AFSecurityPolicy *) customSecurityPolicy { AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; - id<{{classPrefix}}Configuration> config = self.configuration; + {{classPrefix}}Configuration *config = [self configuration]; if (config.sslCaCert) { NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; - [securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]]; + [securityPolicy setPinnedCertificates:@[certData]]; } if (config.verifySSL) { @@ -479,4 +497,8 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) return securityPolicy; } +- ({{classPrefix}}Configuration*) configuration { + return [{{classPrefix}}Configuration sharedConfig]; +} + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache similarity index 59% rename from modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-header.mustache rename to modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index ef3a10a55ed..be5eba32ee0 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -1,10 +1,22 @@ +#import +#import #import +#import "{{classPrefix}}JSONResponseSerializer.h" +#import "{{classPrefix}}JSONRequestSerializer.h" +#import "{{classPrefix}}QueryParamCollection.h" #import "{{classPrefix}}Configuration.h" #import "{{classPrefix}}ResponseDeserializer.h" #import "{{classPrefix}}Sanitizer.h" +#import "{{classPrefix}}Logger.h" {{>licenceInfo}} +{{#models}}{{#model}}#import "{{classname}}.h" +{{/model}}{{/models}} +{{^models}}#import "{{classPrefix}}Object.h"{{/models}} + +@class {{classPrefix}}Configuration; + /** * A key for `NSError` user info dictionaries. * @@ -12,15 +24,15 @@ */ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; - -@interface {{classPrefix}}ApiSessionManager : AFHTTPSessionManager - -@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration; +@interface {{classPrefix}}ApiClient : AFHTTPSessionManager @property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; @property(nonatomic, assign) NSTimeInterval timeoutInterval; @property(nonatomic, readonly) NSOperationQueue* queue; +/// In order to ensure the HTTPResponseHeaders are correct, it is recommended to initialize one {{classPrefix}}ApiClient instance per thread. +@property(nonatomic, readonly) NSDictionary* HTTPResponseHeaders; + @property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer; @property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer; @@ -36,6 +48,13 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ +(void)setCacheEnabled:(BOOL) enabled; +/** + * Gets the request queue size + * + * @return The size of `queuedRequests` static variable. + */ ++(NSUInteger)requestQueueSize; + /** * Sets the client unreachable * @@ -64,6 +83,27 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ +(AFNetworkReachabilityStatus) getReachabilityStatus; +/** + * Gets the next request id + * + * @return The next executed request id. + */ ++(NSNumber*) nextRequestId; + +/** + * Generates request id and add it to the queue + * + * @return The next executed request id. + */ ++(NSNumber*) queueRequest; + +/** + * Removes request id from the queue + * + * @param requestId The request which will be removed. + */ ++(void) cancelRequest:(NSNumber*)requestId; + /** * Customizes the behavior when the reachability changed * @@ -96,14 +136,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings; - -/** - * Initializes the session manager with a configuration. - * - * @param configuration The configuration implementation - */ -- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration; - /** * Performs request * @@ -118,21 +150,21 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; * @param responseContentType Response content-type. * @param completionBlock The block will be executed when the request completed. * - * @return The created session task. + * @return The request id. */ -- (NSURLSessionTask*) requestWithPath: (NSString*) path - method: (NSString*) method - pathParams: (NSDictionary *) pathParams - queryParams: (NSDictionary*) queryParams - formParams: (NSDictionary *) formParams - files: (NSDictionary *) files - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - responseType: (NSString *) responseType - completionBlock: (void (^)(id, NSError *))completionBlock; +-(NSNumber*) requestWithPath:(NSString*) path + method:(NSString*) method + pathParams:(NSDictionary *) pathParams + queryParams:(NSDictionary*) queryParams + formParams:(NSDictionary *) formParams + files:(NSDictionary *) files + body:(id) body + headerParams:(NSDictionary*) headerParams + authSettings:(NSArray *) authSettings + requestContentType:(NSString*) requestContentType + responseContentType:(NSString*) responseContentType + responseType:(NSString *) responseType + completionBlock:(void (^)(id, NSError *))completionBlock; /** * Custom security policy @@ -141,4 +173,12 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ - (AFSecurityPolicy *) customSecurityPolicy; +/** + * {{classPrefix}}Configuration return sharedConfig + * + * @return {{classPrefix}}Configuration + */ +- ({{classPrefix}}Configuration*) configuration; + + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-body.mustache b/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-body.mustache deleted file mode 100644 index a928e5e8f4e..00000000000 --- a/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-body.mustache +++ /dev/null @@ -1,19 +0,0 @@ -#import "{{classPrefix}}BasicAuthTokenProvider.h" - -@implementation {{classPrefix}}BasicAuthTokenProvider - -+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password { - - // return empty string if username and password are empty - if (username.length == 0 && password.length == 0){ - return @""; - } - - NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; - NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; - basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - - return basicAuthCredentials; -} - -@end diff --git a/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-header.mustache b/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-header.mustache deleted file mode 100644 index dfb287568a0..00000000000 --- a/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-header.mustache +++ /dev/null @@ -1,14 +0,0 @@ -/** The `{{classPrefix}}BasicAuthTokenProvider` class creates a basic auth token from username and password. - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - -#import - -@interface {{classPrefix}}BasicAuthTokenProvider : NSObject - -+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password; - -@end \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache similarity index 73% rename from modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-body.mustache rename to modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache index 7c2b6cda20b..1aeca25dd3e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache @@ -1,7 +1,6 @@ -#import "{{classPrefix}}DefaultConfiguration.h" -#import "{{classPrefix}}BasicAuthTokenProvider.h" +#import "{{classPrefix}}Configuration.h" -@interface {{classPrefix}}DefaultConfiguration () +@interface {{classPrefix}}Configuration () @property (nonatomic, strong) NSMutableDictionary *mutableDefaultHeaders; @property (nonatomic, strong) NSMutableDictionary *mutableApiKey; @@ -9,12 +8,12 @@ @end -@implementation {{classPrefix}}DefaultConfiguration +@implementation {{classPrefix}}Configuration #pragma mark - Singleton Methods + (instancetype) sharedConfig { - static {{classPrefix}}DefaultConfiguration *shardConfig = nil; + static {{classPrefix}}Configuration *shardConfig = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ shardConfig = [[self alloc] init]; @@ -27,16 +26,17 @@ - (instancetype) init { self = [super init]; if (self) { - _host = @"{{basePath}}"; - _username = @""; - _password = @""; - _accessToken= @""; - _verifySSL = YES; - _mutableApiKey = [NSMutableDictionary dictionary]; - _mutableApiKeyPrefix = [NSMutableDictionary dictionary]; - _mutableDefaultHeaders = [NSMutableDictionary dictionary]; - {{#httpUserAgent}}_mutableDefaultHeaders[@"User-Agent"] = @"{{httpUserAgent}}"{{/httpUserAgent}}; - _logger = [{{classPrefix}}Logger sharedLogger]; + self.apiClient = nil; + self.host = @"{{basePath}}"; + self.username = @""; + self.password = @""; + self.accessToken= @""; + self.verifySSL = YES; + self.mutableApiKey = [NSMutableDictionary dictionary]; + self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + self.mutableDefaultHeaders = [NSMutableDictionary dictionary]; + self.mutableDefaultHeaders[@"User-Agent"] = {{#httpUserAgent}}@"{{httpUserAgent}}"{{/httpUserAgent}}{{^httpUserAgent}}[NSString stringWithFormat:@"Swagger-Codegen/{{version}}/objc (%@; iOS %@; Scale/%0.2f)",[[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]{{/httpUserAgent}}; + self.logger = [{{classPrefix}}Logger sharedLogger]; } return self; } @@ -58,9 +58,16 @@ } - (NSString *) getBasicAuthToken { + // return empty string if username and password are empty + if (self.username.length == 0 && self.password.length == 0){ + return @""; + } - NSString *basicAuthToken = [{{classPrefix}}BasicAuthTokenProvider createBasicAuthTokenWithUsername:self.username password:self.password]; - return basicAuthToken; + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; + NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; + basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; + + return basicAuthCredentials; } - (NSString *) getAccessToken { diff --git a/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache similarity index 92% rename from modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-header.mustache rename to modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache index f93c864ecfe..e727942a4f2 100644 --- a/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache @@ -1,16 +1,23 @@ #import -#import "{{classPrefix}}Configuration.h" +#import "{{classPrefix}}ApiClient.h" +#import "{{classPrefix}}Logger.h" {{>licenceInfo}} -@interface {{classPrefix}}DefaultConfiguration : NSObject <{{classPrefix}}Configuration> +@class {{classPrefix}}ApiClient; +@interface {{classPrefix}}Configuration : NSObject /** * Default api logger */ @property (nonatomic, strong) {{classPrefix}}Logger * logger; +/** + * Default api client + */ +@property (nonatomic) {{classPrefix}}ApiClient *apiClient; + /** * Default base url */ diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache deleted file mode 100644 index db429a38150..00000000000 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache +++ /dev/null @@ -1,75 +0,0 @@ -#import -#import "{{classPrefix}}Logger.h" - -{{>licenceInfo}} - -@protocol {{classPrefix}}Configuration - -/** - * Api logger - */ -@property (readonly, nonatomic) {{classPrefix}}Logger *logger; - -/** - * Base url - */ -@property (readonly, nonatomic) NSString *host; - -/** - * Api key values for Api Key type Authentication - */ -@property (readonly, nonatomic) NSDictionary *apiKey; - -/** - * Api key prefix values to be prepend to the respective api key - */ -@property (readonly, nonatomic) NSDictionary *apiKeyPrefix; - -/** - * Username for HTTP Basic Authentication - */ -@property (readonly, nonatomic) NSString *username; - -/** - * Password for HTTP Basic Authentication - */ -@property (readonly, nonatomic) NSString *password; - -/** - * Access token for OAuth - */ -@property (readonly, nonatomic) NSString *accessToken; - -/** - * Temp folder for file download - */ -@property (readonly, nonatomic) NSString *tempFolderPath; - -/** - * Debug switch, default false - */ -@property (readonly, nonatomic) BOOL debug; - -/** - * SSL/TLS verification - * Set this to NO to skip verifying SSL certificate when calling API from https server - */ -@property (readonly, nonatomic) BOOL verifySSL; - -/** - * SSL/TLS verification - * Set this to customize the certificate file to verify the peer - */ -@property (readonly, nonatomic) NSString *sslCaCert; - -/** - * Authentication Settings - */ -@property (readonly, nonatomic) NSDictionary *authSettings; - -/** -* Default headers for all services -*/ -@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; - -@end \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-body.mustache b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-body.mustache index b544a1dae58..cec8bdeea27 100644 --- a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-body.mustache @@ -1,4 +1,3 @@ -#import #import "JSONValueTransformer+ISO8601.h" @implementation JSONValueTransformer (ISO8601) diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-header.mustache b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-header.mustache index f621e7184a9..2a8d5b0c9e7 100644 --- a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-header.mustache @@ -1,4 +1,5 @@ #import +#import #import {{>licenceInfo}} diff --git a/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache index 88df6d6c9ae..b4599c34f3f 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache @@ -2,35 +2,6 @@ @implementation {{classPrefix}}Object -/** - * Workaround for JSONModel multithreading issues - * https://github.com/icanzilb/JSONModel/issues/441 - */ -- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err { - static NSMutableSet *classNames; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - classNames = [NSMutableSet new]; - }); - - BOOL initSync; - @synchronized([self class]) - { - NSString *className = NSStringFromClass([self class]); - initSync = ![classNames containsObject:className]; - if(initSync) - { - [classNames addObject:className]; - self = [super initWithDictionary:dict error:err]; - } - } - if(!initSync) - { - self = [super initWithDictionary:dict error:err]; - } - return self; -} - /** * Gets the string presentation of the object. * This method will be called when logging model object using `NSLog`. diff --git a/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-body.mustache b/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-body.mustache index b1c901dbffa..23d0c8eaa86 100644 --- a/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-body.mustache @@ -5,15 +5,11 @@ @synthesize values = _values; @synthesize format = _format; -- (id)initWithValuesAndFormat:(NSArray *)values - format:(NSString *)format { +- (id) initWithValuesAndFormat: (NSArray*) values + format: (NSString*) format { + _values = values; + _format = format; - self = [super init]; - if (self) { - _values = values; - _format = format; - } - return self; } diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index d5354954668..57fdc4ae6a7 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -7,7 +7,7 @@ @interface {{classname}} () -@property (nonatomic, strong, readwrite) NSMutableDictionary *defaultHeaders; +@property (nonatomic, strong) NSMutableDictionary *defaultHeaders; @end @@ -16,14 +16,27 @@ NSString* k{{classname}}ErrorDomain = @"{{classname}}ErrorDomain"; NSInteger k{{classname}}MissingParamErrorCode = 234513; -@synthesize apiSessionManager = _apiSessionManager; +@synthesize apiClient = _apiClient; #pragma mark - Initialize methods --(instancetype) initWithApiSessionManager:({{classPrefix}}ApiSessionManager *)apiSessionManager { +- (instancetype) init { self = [super init]; if (self) { - _apiSessionManager = apiSessionManager; + {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; + if (config.apiClient == nil) { + config.apiClient = [[{{classPrefix}}ApiClient alloc] init]; + } + _apiClient = config.apiClient; + _defaultHeaders = [NSMutableDictionary dictionary]; + } + return self; +} + +- (id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient { + self = [super init]; + if (self) { + _apiClient = apiClient; _defaultHeaders = [NSMutableDictionary dictionary]; } return self; @@ -31,6 +44,15 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; #pragma mark - ++ (instancetype)sharedAPI { + static {{classname}} *sharedAPI; + static dispatch_once_t once; + dispatch_once(&once, ^{ + sharedAPI = [[self alloc] init]; + }); + return sharedAPI; +} + -(NSString*) defaultHeaderForKey:(NSString*)key { return self.defaultHeaders[key]; } @@ -43,6 +65,10 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; [self.defaultHeaders setValue:value forKey:key]; } +-(NSUInteger) requestQueueSize { + return [{{classPrefix}}ApiClient requestQueueSize]; +} + #pragma mark - Api Methods {{#operation}} @@ -53,7 +79,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; /// /// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} /// --(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} +-(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler { {{#allParams}} @@ -92,7 +118,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; {{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}} } {{/queryParams}} - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiSessionManager.configuration.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; [headerParams addEntriesFromDictionary:self.defaultHeaders]; {{#headerParams}} if ({{paramName}} != nil) { @@ -100,7 +126,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; } {{/headerParams}} // HTTP header `Accept` - NSString *acceptHeader = [self.apiSessionManager.sanitizer selectHeaderAccept:@[{{#produces}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[{{#produces}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; if(acceptHeader.length > 0) { headerParams[@"Accept"] = acceptHeader; } @@ -109,7 +135,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [self.apiSessionManager.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; // Authentication setting NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; @@ -133,23 +159,24 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; {{/formParams}} {{/bodyParam}} - return [self.apiSessionManager requestWithPath: resourcePath - method: @"{{httpMethod}}" - pathParams: pathParams - queryParams: queryParams - formParams: formParams - files: localVarFiles - body: bodyParam - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}} - completionBlock: ^(id data, NSError *error) { - if(handler) { - handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error); - } - }]; + return [self.apiClient requestWithPath: resourcePath + method: @"{{httpMethod}}" + pathParams: pathParams + queryParams: queryParams + formParams: formParams + files: localVarFiles + body: bodyParam + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}} + completionBlock: ^(id data, NSError *error) { + if(handler) { + handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error); + } + } + ]; } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache index 12fe8c7b954..abe4cf64eb0 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -11,6 +11,8 @@ extern NSString* k{{classname}}ErrorDomain; extern NSInteger k{{classname}}MissingParamErrorCode; ++(instancetype) sharedAPI; + {{#operations}} {{#operation}} /// {{{summary}}} @@ -21,7 +23,7 @@ extern NSInteger k{{classname}}MissingParamErrorCode; /// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} /// /// @return {{{returnType}}} --(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} +-(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; diff --git a/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache b/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache index 79c9da59ce4..da87a712fa2 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache @@ -1,18 +1,20 @@ #import #import "{{classPrefix}}Object.h" -#import "{{classPrefix}}ApiSessionManager.h" +#import "{{classPrefix}}ApiClient.h" {{>licenceInfo}} @protocol {{classPrefix}}Api -@property(readonly, nonatomic, strong) {{classPrefix}}ApiSessionManager *apiSessionManager; +@property(nonatomic, assign) {{classPrefix}}ApiClient *apiClient; --(instancetype) initWithApiSessionManager:({{classPrefix}}ApiSessionManager *)apiSessionManager; +-(id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient; -(void) addHeader:(NSString*)value forKey:(NSString*)key DEPRECATED_MSG_ATTRIBUTE("setDefaultHeaderValue:forKey:"); -(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; -(NSString*) defaultHeaderForKey:(NSString*)key; +-(NSUInteger) requestQueueSize; + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache index 7a2b22bea28..bd0bd9f328e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache @@ -32,6 +32,6 @@ Pod::Spec.new do |s| s.dependency 'AFNetworking', '~> 3' s.dependency 'JSONModel', '~> 1.2' - s.dependency 'ISO8601', '~> 0.6' + s.dependency 'ISO8601', '~> 0.5' end