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 e028083a74..a8522f403d 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("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h")); - supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.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("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,8 +259,11 @@ 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-body.mustache", coreFileFolder(), classPrefix + "Configuration.m")); - supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.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("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/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-body.mustache similarity index 76% rename from modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache rename to modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-body.mustache index 10cb6528d8..6b454063ad 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-body.mustache @@ -1,10 +1,16 @@ -#import "{{classPrefix}}ApiClient.h" +#import + +#import "{{classPrefix}}ApiSessionManager.h" +#import "{{classPrefix}}JSONRequestSerializer.h" +#import "{{classPrefix}}JSONResponseSerializer.h" +#import "{{classPrefix}}QueryParamCollection.h" +#import "{{classPrefix}}DefaultConfiguration.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); @@ -34,40 +40,50 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) } -@interface {{classPrefix}}ApiClient () +@interface {{classPrefix}}ApiSessionManager () -@property (nonatomic, strong) NSDictionary* HTTPResponseHeaders; +@property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration; @end -@implementation {{classPrefix}}ApiClient +@implementation {{classPrefix}}ApiSessionManager - (instancetype)init { - NSString *baseUrl = [[{{classPrefix}}Configuration sharedConfig] host]; - return [self initWithBaseURL:[NSURL URLWithString:baseUrl]]; + + return [self initWithConfiguration:[{{classPrefix}}DefaultConfiguration sharedConfig]]; } - (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) { - self.timeoutInterval = 60; + _configuration = configuration; + _timeoutInterval = 60; + _responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init]; + _sanitizer = [[{{classPrefix}}Sanitizer alloc] init]; + 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]; - } + return self; } #pragma mark - Setter Methods @@ -113,43 +129,6 @@ 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 { @@ -168,7 +147,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { reachabilityStatus = status; {{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); - [{{classPrefix}}ApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; + [{{classPrefix}}ApiSessionManager setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; // call the reachability block, if configured if (reachabilityChangeBlock != nil) { @@ -179,23 +158,19 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [self.reachabilityManager startMonitoring]; } -#pragma mark - Operation Methods +#pragma mark - Task Methods -- (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; - } +- (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); - strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); + if(!error) { completionBlock(responseObject, nil); return; } + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; if (responseObject) { // Add in the (parsed) response body. @@ -204,20 +179,18 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; completionBlock(nil, augmentedError); }]; - [op resume]; + + return task; } -- (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); +- (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) { {{classPrefix}}DebugLogResponse(response, responseObject,request,error); + if(error) { NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; if (responseObject) { @@ -226,8 +199,9 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; completionBlock(nil, augmentedError); } - NSString *directory = [self configuration].tempFolderPath ?: NSTemporaryDirectory(); - NSString * filename = {{classPrefix}}__fileNameForResponse(response); + + NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory(); + NSString *filename = {{classPrefix}}__fileNameForResponse(response); NSString *filepath = [directory stringByAppendingPathComponent:filename]; NSURL *file = [NSURL fileURLWithPath:filepath]; @@ -236,24 +210,26 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) completionBlock(file, nil); }]; - [op resume]; + + return task; } -#pragma mark - Perform Request Methods +#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 { --(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]; @@ -359,14 +335,16 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [self postProcessRequest:request]; - NSNumber* requestId = [{{classPrefix}}ApiClient queueRequest]; + + NSURLSessionTask *task = nil; + if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { - [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { completionBlock(data, error); }]; } else { - [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { NSError * serializationError; id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; if(!response && !error){ @@ -375,7 +353,10 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) completionBlock(response, error); }]; } - return requestId; + + [task resume]; + + return task; } //Added for easier override to modify request @@ -455,10 +436,11 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; - - NSDictionary* configurationAuthSettings = [[self configuration] authSettings]; + + id<{{classPrefix}}Configuration> config = self.configuration; for (NSString *auth in authSettings) { - NSDictionary *authSetting = configurationAuthSettings[auth]; + NSDictionary *authSetting = config.authSettings[auth]; + if(!authSetting) { // auth setting is set only if the key is non-empty continue; } @@ -479,11 +461,11 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) - (AFSecurityPolicy *) customSecurityPolicy { AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; - {{classPrefix}}Configuration *config = [self configuration]; + id<{{classPrefix}}Configuration> config = self.configuration; if (config.sslCaCert) { NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; - [securityPolicy setPinnedCertificates:@[certData]]; + [securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]]; } if (config.verifySSL) { @@ -497,8 +479,4 @@ 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/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-header.mustache similarity index 59% rename from modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache rename to modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-header.mustache index be5eba32ee..ef3a10a55e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-header.mustache @@ -1,22 +1,10 @@ -#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. * @@ -24,15 +12,15 @@ */ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; -@interface {{classPrefix}}ApiClient : AFHTTPSessionManager + +@interface {{classPrefix}}ApiSessionManager : AFHTTPSessionManager + +@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration; @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; @@ -48,13 +36,6 @@ 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 * @@ -83,27 +64,6 @@ 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 * @@ -136,6 +96,14 @@ 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 * @@ -150,21 +118,21 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; * @param responseContentType Response content-type. * @param completionBlock The block will be executed when the request completed. * - * @return The request id. + * @return The created session task. */ --(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; +- (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; /** * Custom security policy @@ -173,12 +141,4 @@ 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 new file mode 100644 index 0000000000..a928e5e8f4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-body.mustache @@ -0,0 +1,19 @@ +#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 new file mode 100644 index 0000000000..dfb287568a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-header.mustache @@ -0,0 +1,14 @@ +/** 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/Configuration-protocol.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache new file mode 100644 index 0000000000..db429a3815 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache @@ -0,0 +1,75 @@ +#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/Configuration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-body.mustache similarity index 76% rename from modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache rename to modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-body.mustache index c1819d7fe1..7c2b6cda20 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-body.mustache @@ -1,6 +1,7 @@ -#import "{{classPrefix}}Configuration.h" +#import "{{classPrefix}}DefaultConfiguration.h" +#import "{{classPrefix}}BasicAuthTokenProvider.h" -@interface {{classPrefix}}Configuration () +@interface {{classPrefix}}DefaultConfiguration () @property (nonatomic, strong) NSMutableDictionary *mutableDefaultHeaders; @property (nonatomic, strong) NSMutableDictionary *mutableApiKey; @@ -8,12 +9,12 @@ @end -@implementation {{classPrefix}}Configuration +@implementation {{classPrefix}}DefaultConfiguration #pragma mark - Singleton Methods + (instancetype) sharedConfig { - static {{classPrefix}}Configuration *shardConfig = nil; + static {{classPrefix}}DefaultConfiguration *shardConfig = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ shardConfig = [[self alloc] init]; @@ -26,17 +27,16 @@ - (instancetype) init { self = [super init]; if (self) { - 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]; - {{#httpUserAgent}}self.mutableDefaultHeaders[@"User-Agent"] = @"{{httpUserAgent}}"{{/httpUserAgent}}; - self.logger = [{{classPrefix}}Logger sharedLogger]; + _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]; } return self; } @@ -58,16 +58,9 @@ } - (NSString *) getBasicAuthToken { - // return empty string if username and password are empty - if (self.username.length == 0 && self.password.length == 0){ - return @""; - } - NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; - NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; - basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - - return basicAuthCredentials; + NSString *basicAuthToken = [{{classPrefix}}BasicAuthTokenProvider createBasicAuthTokenWithUsername:self.username password:self.password]; + return basicAuthToken; } - (NSString *) getAccessToken { diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-header.mustache similarity index 92% rename from modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache rename to modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-header.mustache index e727942a4f..f93c864ecf 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-header.mustache @@ -1,23 +1,16 @@ #import -#import "{{classPrefix}}ApiClient.h" -#import "{{classPrefix}}Logger.h" +#import "{{classPrefix}}Configuration.h" {{>licenceInfo}} -@class {{classPrefix}}ApiClient; +@interface {{classPrefix}}DefaultConfiguration : NSObject <{{classPrefix}}Configuration> -@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/JSONValueTransformer+ISO8601-body.mustache b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-body.mustache index cec8bdeea2..b544a1dae5 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,3 +1,4 @@ +#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 2a8d5b0c9e..f621e7184a 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,5 +1,4 @@ #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 b4599c34f3..88df6d6c9a 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache @@ -2,6 +2,35 @@ @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 23d0c8eaa8..b1c901dbff 100644 --- a/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-body.mustache @@ -5,11 +5,15 @@ @synthesize values = _values; @synthesize format = _format; -- (id) initWithValuesAndFormat: (NSArray*) values - format: (NSString*) format { - _values = values; - _format = format; +- (id)initWithValuesAndFormat:(NSArray *)values + format:(NSString *)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 57fdc4ae6a..d535495466 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) NSMutableDictionary *defaultHeaders; +@property (nonatomic, strong, readwrite) NSMutableDictionary *defaultHeaders; @end @@ -16,27 +16,14 @@ NSString* k{{classname}}ErrorDomain = @"{{classname}}ErrorDomain"; NSInteger k{{classname}}MissingParamErrorCode = 234513; -@synthesize apiClient = _apiClient; +@synthesize apiSessionManager = _apiSessionManager; #pragma mark - Initialize methods -- (instancetype) init { +-(instancetype) initWithApiSessionManager:({{classPrefix}}ApiSessionManager *)apiSessionManager { self = [super init]; if (self) { - {{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; + _apiSessionManager = apiSessionManager; _defaultHeaders = [NSMutableDictionary dictionary]; } return self; @@ -44,15 +31,6 @@ 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]; } @@ -65,10 +43,6 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; [self.defaultHeaders setValue:value forKey:key]; } --(NSUInteger) requestQueueSize { - return [{{classPrefix}}ApiClient requestQueueSize]; -} - #pragma mark - Api Methods {{#operation}} @@ -79,7 +53,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; /// /// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} /// --(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}} +-(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}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler { {{#allParams}} @@ -118,7 +92,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; {{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}} } {{/queryParams}} - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiSessionManager.configuration.defaultHeaders]; [headerParams addEntriesFromDictionary:self.defaultHeaders]; {{#headerParams}} if ({{paramName}} != nil) { @@ -126,7 +100,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; } {{/headerParams}} // HTTP header `Accept` - NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[{{#produces}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; + NSString *acceptHeader = [self.apiSessionManager.sanitizer selectHeaderAccept:@[{{#produces}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; if(acceptHeader.length > 0) { headerParams[@"Accept"] = acceptHeader; } @@ -135,7 +109,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; + NSString *requestContentType = [self.apiSessionManager.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; // Authentication setting NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; @@ -159,24 +133,23 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; {{/formParams}} {{/bodyParam}} - 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); - } - } - ]; + 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); + } + }]; } {{/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 abe4cf64eb..12fe8c7b95 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -11,8 +11,6 @@ extern NSString* k{{classname}}ErrorDomain; extern NSInteger k{{classname}}MissingParamErrorCode; -+(instancetype) sharedAPI; - {{#operations}} {{#operation}} /// {{{summary}}} @@ -23,7 +21,7 @@ extern NSInteger k{{classname}}MissingParamErrorCode; /// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} /// /// @return {{{returnType}}} --(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}} +-(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}} {{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 da87a712fa..79c9da59ce 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache @@ -1,20 +1,18 @@ #import #import "{{classPrefix}}Object.h" -#import "{{classPrefix}}ApiClient.h" +#import "{{classPrefix}}ApiSessionManager.h" {{>licenceInfo}} @protocol {{classPrefix}}Api -@property(nonatomic, assign) {{classPrefix}}ApiClient *apiClient; +@property(readonly, nonatomic, strong) {{classPrefix}}ApiSessionManager *apiSessionManager; --(id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient; +-(instancetype) initWithApiSessionManager:({{classPrefix}}ApiSessionManager *)apiSessionManager; -(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 bd0bd9f328..7a2b22bea2 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.5' + s.dependency 'ISO8601', '~> 0.6' end