Merge branch 'feature/objc-tasks' of https://github.com/wberger/swagger-codegen

This commit is contained in:
wing328 2016-07-30 16:17:08 +08:00
commit 7c1daab896
16 changed files with 315 additions and 278 deletions

View File

@ -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("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m"));
supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h")); supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h"));
supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m")); supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m"));
supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h")); supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", coreFileFolder(), classPrefix + "ApiSessionManager.h"));
supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m")); 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-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h"));
supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m")); supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m"));
supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m"));
@ -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("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-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m"));
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h")); 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-protocol.mustache", coreFileFolder(), classPrefix + "Configuration.h"));
supportingFiles.add(new SupportingFile("Configuration-header.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("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h"));
supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));

View File

@ -1,10 +1,16 @@
#import "{{classPrefix}}ApiClient.h" #import <ISO8601/NSDate+ISO8601.h>
#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"; NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject";
static NSUInteger requestId = 0;
static bool offlineState = false; static bool offlineState = false;
static NSMutableSet * queuedRequests = nil;
static bool cacheEnabled = false; static bool cacheEnabled = false;
static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable;
static void (^reachabilityChangeBlock)(int); 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 @end
@implementation {{classPrefix}}ApiClient @implementation {{classPrefix}}ApiSessionManager
- (instancetype)init { - (instancetype)init {
NSString *baseUrl = [[{{classPrefix}}Configuration sharedConfig] host];
return [self initWithBaseURL:[NSURL URLWithString:baseUrl]]; return [self initWithConfiguration:[{{classPrefix}}DefaultConfiguration sharedConfig]];
} }
- (instancetype)initWithBaseURL:(NSURL *)url { - (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]; self = [super initWithBaseURL:url];
if (self) { if (self) {
self.timeoutInterval = 60; _configuration = configuration;
_timeoutInterval = 60;
_responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init];
_sanitizer = [[{{classPrefix}}Sanitizer alloc] init];
self.requestSerializer = [AFJSONRequestSerializer serializer]; self.requestSerializer = [AFJSONRequestSerializer serializer];
self.responseSerializer = [AFJSONResponseSerializer serializer]; self.responseSerializer = [AFJSONResponseSerializer serializer];
self.securityPolicy = [self customSecurityPolicy]; self.securityPolicy = [self customSecurityPolicy];
self.responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init];
self.sanitizer = [[{{classPrefix}}Sanitizer alloc] init];
// configure reachability // configure reachability
[self configureCacheReachibility]; [self configureCacheReachibility];
} }
return self;
}
+ (void)initialize { return self;
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 #pragma mark - Setter Methods
@ -113,43 +129,6 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
[NSURLCache setSharedURLCache:cache]; [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 #pragma mark - Reachability Methods
+(AFNetworkReachabilityStatus) getReachabilityStatus { +(AFNetworkReachabilityStatus) getReachabilityStatus {
@ -168,7 +147,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
reachabilityStatus = status; reachabilityStatus = status;
{{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(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 // call the reachability block, if configured
if (reachabilityChangeBlock != nil) { if (reachabilityChangeBlock != nil) {
@ -179,23 +158,19 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
[self.reachabilityManager startMonitoring]; [self.reachabilityManager startMonitoring];
} }
#pragma mark - Operation Methods #pragma mark - Task Methods
- (void) operationWithCompletionBlock: (NSURLRequest *)request - (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request
requestId: (NSNumber *) requestId
completionBlock: (void (^)(id, NSError *))completionBlock { completionBlock: (void (^)(id, NSError *))completionBlock {
__weak __typeof(self)weakSelf = self;
NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
if (![strongSelf executeRequestWithId:requestId]) {
return;
}
{{classPrefix}}DebugLogResponse(response, responseObject,request,error); {{classPrefix}}DebugLogResponse(response, responseObject,request,error);
strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response);
if(!error) { if(!error) {
completionBlock(responseObject, nil); completionBlock(responseObject, nil);
return; return;
} }
NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
if (responseObject) { if (responseObject) {
// Add in the (parsed) response body. // Add in the (parsed) response body.
@ -204,20 +179,18 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
completionBlock(nil, augmentedError); completionBlock(nil, augmentedError);
}]; }];
[op resume];
return task;
} }
- (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request - (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request
requestId: (NSNumber *) requestId
completionBlock: (void (^)(id, NSError *))completionBlock { completionBlock: (void (^)(id, NSError *))completionBlock {
__weak __typeof(self)weakSelf = self;
NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { id<{{classPrefix}}Configuration> config = self.configuration;
__strong __typeof(weakSelf)strongSelf = weakSelf;
if (![strongSelf executeRequestWithId:requestId]) { NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
return;
}
strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response);
{{classPrefix}}DebugLogResponse(response, responseObject,request,error); {{classPrefix}}DebugLogResponse(response, responseObject,request,error);
if(error) { if(error) {
NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
if (responseObject) { if (responseObject) {
@ -226,8 +199,9 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
completionBlock(nil, augmentedError); completionBlock(nil, augmentedError);
} }
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]; NSString *filepath = [directory stringByAppendingPathComponent:filename];
NSURL *file = [NSURL fileURLWithPath:filepath]; NSURL *file = [NSURL fileURLWithPath:filepath];
@ -236,12 +210,13 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
completionBlock(file, nil); completionBlock(file, nil);
}]; }];
[op resume];
return task;
} }
#pragma mark - Perform Request Methods #pragma mark - Perform Request Methods
-(NSNumber*) requestWithPath: (NSString*) path - (NSURLSessionTask*) requestWithPath: (NSString*) path
method: (NSString*) method method: (NSString*) method
pathParams: (NSDictionary *) pathParams pathParams: (NSDictionary *) pathParams
queryParams: (NSDictionary*) queryParams queryParams: (NSDictionary*) queryParams
@ -254,6 +229,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
responseContentType: (NSString*) responseContentType responseContentType: (NSString*) responseContentType
responseType: (NSString *) responseType responseType: (NSString *) responseType
completionBlock: (void (^)(id, NSError *))completionBlock { completionBlock: (void (^)(id, NSError *))completionBlock {
// setting request serializer // setting request serializer
if ([requestContentType isEqualToString:@"application/json"]) { if ([requestContentType isEqualToString:@"application/json"]) {
self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer]; self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer];
@ -359,14 +335,16 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
[self postProcessRequest:request]; [self postProcessRequest:request];
NSNumber* requestId = [{{classPrefix}}ApiClient queueRequest];
NSURLSessionTask *task = nil;
if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { 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); completionBlock(data, error);
}]; }];
} }
else { else {
[self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
NSError * serializationError; NSError * serializationError;
id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError];
if(!response && !error){ if(!response && !error){
@ -375,7 +353,10 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
completionBlock(response, error); completionBlock(response, error);
}]; }];
} }
return requestId;
[task resume];
return task;
} }
//Added for easier override to modify request //Added for easier override to modify request
@ -456,9 +437,10 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers];
NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys];
NSDictionary* configurationAuthSettings = [[self configuration] authSettings]; id<{{classPrefix}}Configuration> config = self.configuration;
for (NSString *auth in authSettings) { 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 if(!authSetting) { // auth setting is set only if the key is non-empty
continue; continue;
} }
@ -479,11 +461,11 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
- (AFSecurityPolicy *) customSecurityPolicy { - (AFSecurityPolicy *) customSecurityPolicy {
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
{{classPrefix}}Configuration *config = [self configuration]; id<{{classPrefix}}Configuration> config = self.configuration;
if (config.sslCaCert) { if (config.sslCaCert) {
NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert];
[securityPolicy setPinnedCertificates:@[certData]]; [securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]];
} }
if (config.verifySSL) { if (config.verifySSL) {
@ -497,8 +479,4 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
return securityPolicy; return securityPolicy;
} }
- ({{classPrefix}}Configuration*) configuration {
return [{{classPrefix}}Configuration sharedConfig];
}
@end @end

View File

@ -1,22 +1,10 @@
#import <Foundation/Foundation.h>
#import <ISO8601/ISO8601.h>
#import <AFNetworking/AFNetworking.h> #import <AFNetworking/AFNetworking.h>
#import "{{classPrefix}}JSONResponseSerializer.h"
#import "{{classPrefix}}JSONRequestSerializer.h"
#import "{{classPrefix}}QueryParamCollection.h"
#import "{{classPrefix}}Configuration.h" #import "{{classPrefix}}Configuration.h"
#import "{{classPrefix}}ResponseDeserializer.h" #import "{{classPrefix}}ResponseDeserializer.h"
#import "{{classPrefix}}Sanitizer.h" #import "{{classPrefix}}Sanitizer.h"
#import "{{classPrefix}}Logger.h"
{{>licenceInfo}} {{>licenceInfo}}
{{#models}}{{#model}}#import "{{classname}}.h"
{{/model}}{{/models}}
{{^models}}#import "{{classPrefix}}Object.h"{{/models}}
@class {{classPrefix}}Configuration;
/** /**
* A key for `NSError` user info dictionaries. * A key for `NSError` user info dictionaries.
* *
@ -24,15 +12,15 @@
*/ */
extern NSString *const {{classPrefix}}ResponseObjectErrorKey; 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) NSURLRequestCachePolicy cachePolicy;
@property(nonatomic, assign) NSTimeInterval timeoutInterval; @property(nonatomic, assign) NSTimeInterval timeoutInterval;
@property(nonatomic, readonly) NSOperationQueue* queue; @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}}ResponseDeserializer> responseDeserializer;
@property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer; @property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer;
@ -48,13 +36,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
*/ */
+(void)setCacheEnabled:(BOOL) enabled; +(void)setCacheEnabled:(BOOL) enabled;
/**
* Gets the request queue size
*
* @return The size of `queuedRequests` static variable.
*/
+(NSUInteger)requestQueueSize;
/** /**
* Sets the client unreachable * Sets the client unreachable
* *
@ -83,27 +64,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
*/ */
+(AFNetworkReachabilityStatus) getReachabilityStatus; +(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 * Customizes the behavior when the reachability changed
* *
@ -136,6 +96,14 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
queryParams:(NSDictionary **)querys queryParams:(NSDictionary **)querys
WithAuthSettings:(NSArray *)authSettings; WithAuthSettings:(NSArray *)authSettings;
/**
* Initializes the session manager with a configuration.
*
* @param configuration The configuration implementation
*/
- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration;
/** /**
* Performs request * Performs request
* *
@ -150,21 +118,21 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
* @param responseContentType Response content-type. * @param responseContentType Response content-type.
* @param completionBlock The block will be executed when the request completed. * @param completionBlock The block will be executed when the request completed.
* *
* @return The request id. * @return The created session task.
*/ */
-(NSNumber*) requestWithPath:(NSString*) path - (NSURLSessionTask*) requestWithPath: (NSString*) path
method:(NSString*) method method: (NSString*) method
pathParams:(NSDictionary *) pathParams pathParams: (NSDictionary *) pathParams
queryParams:(NSDictionary*) queryParams queryParams: (NSDictionary*) queryParams
formParams:(NSDictionary *) formParams formParams: (NSDictionary *) formParams
files:(NSDictionary *) files files: (NSDictionary *) files
body:(id) body body: (id) body
headerParams:(NSDictionary*) headerParams headerParams: (NSDictionary*) headerParams
authSettings:(NSArray *) authSettings authSettings: (NSArray *) authSettings
requestContentType:(NSString*) requestContentType requestContentType: (NSString*) requestContentType
responseContentType:(NSString*) responseContentType responseContentType: (NSString*) responseContentType
responseType:(NSString *) responseType responseType: (NSString *) responseType
completionBlock:(void (^)(id, NSError *))completionBlock; completionBlock: (void (^)(id, NSError *))completionBlock;
/** /**
* Custom security policy * Custom security policy
@ -173,12 +141,4 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
*/ */
- (AFSecurityPolicy *) customSecurityPolicy; - (AFSecurityPolicy *) customSecurityPolicy;
/**
* {{classPrefix}}Configuration return sharedConfig
*
* @return {{classPrefix}}Configuration
*/
- ({{classPrefix}}Configuration*) configuration;
@end @end

View File

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

View File

@ -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 <Foundation/Foundation.h>
@interface {{classPrefix}}BasicAuthTokenProvider : NSObject
+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password;
@end

View File

@ -0,0 +1,75 @@
#import <Foundation/Foundation.h>
#import "{{classPrefix}}Logger.h"
{{>licenceInfo}}
@protocol {{classPrefix}}Configuration <NSObject>
/**
* 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

View File

@ -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 *mutableDefaultHeaders;
@property (nonatomic, strong) NSMutableDictionary *mutableApiKey; @property (nonatomic, strong) NSMutableDictionary *mutableApiKey;
@ -8,12 +9,12 @@
@end @end
@implementation {{classPrefix}}Configuration @implementation {{classPrefix}}DefaultConfiguration
#pragma mark - Singleton Methods #pragma mark - Singleton Methods
+ (instancetype) sharedConfig { + (instancetype) sharedConfig {
static {{classPrefix}}Configuration *shardConfig = nil; static {{classPrefix}}DefaultConfiguration *shardConfig = nil;
static dispatch_once_t onceToken; static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ dispatch_once(&onceToken, ^{
shardConfig = [[self alloc] init]; shardConfig = [[self alloc] init];
@ -26,17 +27,16 @@
- (instancetype) init { - (instancetype) init {
self = [super init]; self = [super init];
if (self) { if (self) {
self.apiClient = nil; _host = @"{{basePath}}";
self.host = @"{{basePath}}"; _username = @"";
self.username = @""; _password = @"";
self.password = @""; _accessToken= @"";
self.accessToken= @""; _verifySSL = YES;
self.verifySSL = YES; _mutableApiKey = [NSMutableDictionary dictionary];
self.mutableApiKey = [NSMutableDictionary dictionary]; _mutableApiKeyPrefix = [NSMutableDictionary dictionary];
self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; _mutableDefaultHeaders = [NSMutableDictionary dictionary];
self.mutableDefaultHeaders = [NSMutableDictionary dictionary]; {{#httpUserAgent}}_mutableDefaultHeaders[@"User-Agent"] = @"{{httpUserAgent}}"{{/httpUserAgent}};
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}}; _logger = [{{classPrefix}}Logger sharedLogger];
self.logger = [{{classPrefix}}Logger sharedLogger];
} }
return self; return self;
} }
@ -58,16 +58,9 @@
} }
- (NSString *) getBasicAuthToken { - (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]; NSString *basicAuthToken = [{{classPrefix}}BasicAuthTokenProvider createBasicAuthTokenWithUsername:self.username password:self.password];
NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; return basicAuthToken;
basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]];
return basicAuthCredentials;
} }
- (NSString *) getAccessToken { - (NSString *) getAccessToken {

View File

@ -1,23 +1,16 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import "{{classPrefix}}ApiClient.h" #import "{{classPrefix}}Configuration.h"
#import "{{classPrefix}}Logger.h"
{{>licenceInfo}} {{>licenceInfo}}
@class {{classPrefix}}ApiClient; @interface {{classPrefix}}DefaultConfiguration : NSObject <{{classPrefix}}Configuration>
@interface {{classPrefix}}Configuration : NSObject
/** /**
* Default api logger * Default api logger
*/ */
@property (nonatomic, strong) {{classPrefix}}Logger * logger; @property (nonatomic, strong) {{classPrefix}}Logger * logger;
/**
* Default api client
*/
@property (nonatomic) {{classPrefix}}ApiClient *apiClient;
/** /**
* Default base url * Default base url
*/ */

View File

@ -1,3 +1,4 @@
#import <ISO8601/NSDate+ISO8601.h>
#import "JSONValueTransformer+ISO8601.h" #import "JSONValueTransformer+ISO8601.h"
@implementation JSONValueTransformer (ISO8601) @implementation JSONValueTransformer (ISO8601)

View File

@ -1,5 +1,4 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <ISO8601/ISO8601.h>
#import <JSONModel/JSONValueTransformer.h> #import <JSONModel/JSONValueTransformer.h>
{{>licenceInfo}} {{>licenceInfo}}

View File

@ -2,6 +2,35 @@
@implementation {{classPrefix}}Object @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. * Gets the string presentation of the object.
* This method will be called when logging model object using `NSLog`. * This method will be called when logging model object using `NSLog`.

View File

@ -5,10 +5,14 @@
@synthesize values = _values; @synthesize values = _values;
@synthesize format = _format; @synthesize format = _format;
- (id) initWithValuesAndFormat: (NSArray*) values - (id)initWithValuesAndFormat:(NSArray *)values
format: (NSString*) format { format:(NSString *)format {
self = [super init];
if (self) {
_values = values; _values = values;
_format = format; _format = format;
}
return self; return self;
} }

View File

@ -7,7 +7,7 @@
@interface {{classname}} () @interface {{classname}} ()
@property (nonatomic, strong) NSMutableDictionary *defaultHeaders; @property (nonatomic, strong, readwrite) NSMutableDictionary *defaultHeaders;
@end @end
@ -16,27 +16,14 @@
NSString* k{{classname}}ErrorDomain = @"{{classname}}ErrorDomain"; NSString* k{{classname}}ErrorDomain = @"{{classname}}ErrorDomain";
NSInteger k{{classname}}MissingParamErrorCode = 234513; NSInteger k{{classname}}MissingParamErrorCode = 234513;
@synthesize apiClient = _apiClient; @synthesize apiSessionManager = _apiSessionManager;
#pragma mark - Initialize methods #pragma mark - Initialize methods
- (instancetype) init { -(instancetype) initWithApiSessionManager:({{classPrefix}}ApiSessionManager *)apiSessionManager {
self = [super init]; self = [super init];
if (self) { if (self) {
{{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; _apiSessionManager = apiSessionManager;
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]; _defaultHeaders = [NSMutableDictionary dictionary];
} }
return self; return self;
@ -44,15 +31,6 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513;
#pragma mark - #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 { -(NSString*) defaultHeaderForKey:(NSString*)key {
return self.defaultHeaders[key]; return self.defaultHeaders[key];
} }
@ -65,10 +43,6 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513;
[self.defaultHeaders setValue:value forKey:key]; [self.defaultHeaders setValue:value forKey:key];
} }
-(NSUInteger) requestQueueSize {
return [{{classPrefix}}ApiClient requestQueueSize];
}
#pragma mark - Api Methods #pragma mark - Api Methods
{{#operation}} {{#operation}}
@ -79,7 +53,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513;
/// ///
/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} /// {{/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}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}}
{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler { {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler {
{{#allParams}} {{#allParams}}
@ -118,7 +92,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513;
{{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}} {{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}}
} }
{{/queryParams}} {{/queryParams}}
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiSessionManager.configuration.defaultHeaders];
[headerParams addEntriesFromDictionary:self.defaultHeaders]; [headerParams addEntriesFromDictionary:self.defaultHeaders];
{{#headerParams}} {{#headerParams}}
if ({{paramName}} != nil) { if ({{paramName}} != nil) {
@ -126,7 +100,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513;
} }
{{/headerParams}} {{/headerParams}}
// HTTP header `Accept` // 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) { if(acceptHeader.length > 0) {
headerParams[@"Accept"] = acceptHeader; headerParams[@"Accept"] = acceptHeader;
} }
@ -135,7 +109,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513;
NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @"";
// request content type // 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 // Authentication setting
NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}];
@ -159,7 +133,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513;
{{/formParams}} {{/formParams}}
{{/bodyParam}} {{/bodyParam}}
return [self.apiClient requestWithPath: resourcePath return [self.apiSessionManager requestWithPath: resourcePath
method: @"{{httpMethod}}" method: @"{{httpMethod}}"
pathParams: pathParams pathParams: pathParams
queryParams: queryParams queryParams: queryParams
@ -175,8 +149,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513;
if(handler) { if(handler) {
handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error); handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error);
} }
} }];
];
} }
{{/operation}} {{/operation}}

View File

@ -11,8 +11,6 @@
extern NSString* k{{classname}}ErrorDomain; extern NSString* k{{classname}}ErrorDomain;
extern NSInteger k{{classname}}MissingParamErrorCode; extern NSInteger k{{classname}}MissingParamErrorCode;
+(instancetype) sharedAPI;
{{#operations}} {{#operations}}
{{#operation}} {{#operation}}
/// {{{summary}}} /// {{{summary}}}
@ -23,7 +21,7 @@ extern NSInteger k{{classname}}MissingParamErrorCode;
/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} /// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}}
/// ///
/// @return {{{returnType}}} /// @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}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}}
{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler;

View File

@ -1,20 +1,18 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import "{{classPrefix}}Object.h" #import "{{classPrefix}}Object.h"
#import "{{classPrefix}}ApiClient.h" #import "{{classPrefix}}ApiSessionManager.h"
{{>licenceInfo}} {{>licenceInfo}}
@protocol {{classPrefix}}Api <NSObject> @protocol {{classPrefix}}Api <NSObject>
@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) addHeader:(NSString*)value forKey:(NSString*)key DEPRECATED_MSG_ATTRIBUTE("setDefaultHeaderValue:forKey:");
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; -(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key;
-(NSString*) defaultHeaderForKey:(NSString*)key; -(NSString*) defaultHeaderForKey:(NSString*)key;
-(NSUInteger) requestQueueSize;
@end @end

View File

@ -32,6 +32,6 @@ Pod::Spec.new do |s|
s.dependency 'AFNetworking', '~> 3' s.dependency 'AFNetworking', '~> 3'
s.dependency 'JSONModel', '~> 1.2' s.dependency 'JSONModel', '~> 1.2'
s.dependency 'ISO8601', '~> 0.5' s.dependency 'ISO8601', '~> 0.6'
end end