mirror of
https://github.com/valitydev/openapi-generator.git
synced 2024-11-07 02:55:19 +00:00
rename ApiClient to ApiSessionManager, return cancellable tasks instead of request IDs which greatly reduces state while offering real cancellation, change to a protocol-based configuration with a default implementation, include a workarount for current JSONModel concurrency issues, add missing super call in QueryParamCollection initWithValuesAndFormat
This commit is contained in:
parent
e73f2a5c64
commit
f37bd4ab49
@ -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"));
|
||||
|
@ -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";
|
||||
|
||||
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
|
||||
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request
|
||||
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 *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
|
||||
- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request
|
||||
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);
|
||||
|
||||
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,7 +199,8 @@ 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 *directory = config.tempFolderPath ?: NSTemporaryDirectory();
|
||||
NSString *filename = {{classPrefix}}__fileNameForResponse(response);
|
||||
|
||||
NSString *filepath = [directory stringByAppendingPathComponent:filename];
|
||||
@ -236,12 +210,13 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
|
||||
|
||||
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
|
||||
pathParams: (NSDictionary *) pathParams
|
||||
queryParams: (NSDictionary*) queryParams
|
||||
@ -254,6 +229,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
|
||||
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
|
||||
@ -456,9 +437,10 @@ 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
|
@ -1,22 +1,10 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <ISO8601/ISO8601.h>
|
||||
#import <AFNetworking/AFNetworking.h>
|
||||
#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,9 +118,9 @@ 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
|
||||
- (NSURLSessionTask*) requestWithPath: (NSString*) path
|
||||
method: (NSString*) method
|
||||
pathParams: (NSDictionary *) pathParams
|
||||
queryParams: (NSDictionary*) queryParams
|
||||
@ -173,12 +141,4 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
|
||||
*/
|
||||
- (AFSecurityPolicy *) customSecurityPolicy;
|
||||
|
||||
/**
|
||||
* {{classPrefix}}Configuration return sharedConfig
|
||||
*
|
||||
* @return {{classPrefix}}Configuration
|
||||
*/
|
||||
- ({{classPrefix}}Configuration*) configuration;
|
||||
|
||||
|
||||
@end
|
@ -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
|
@ -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
|
@ -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
|
@ -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 {
|
@ -1,23 +1,16 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#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
|
||||
*/
|
@ -1,3 +1,4 @@
|
||||
#import <ISO8601/NSDate+ISO8601.h>
|
||||
#import "JSONValueTransformer+ISO8601.h"
|
||||
|
||||
@implementation JSONValueTransformer (ISO8601)
|
||||
|
@ -1,5 +1,4 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <ISO8601/ISO8601.h>
|
||||
#import <JSONModel/JSONValueTransformer.h>
|
||||
|
||||
{{>licenceInfo}}
|
||||
|
@ -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`.
|
||||
|
@ -7,8 +7,12 @@
|
||||
|
||||
- (id)initWithValuesAndFormat:(NSArray *)values
|
||||
format:(NSString *)format {
|
||||
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_values = values;
|
||||
_format = format;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
@ -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,7 +133,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513;
|
||||
{{/formParams}}
|
||||
{{/bodyParam}}
|
||||
|
||||
return [self.apiClient requestWithPath: resourcePath
|
||||
return [self.apiSessionManager requestWithPath: resourcePath
|
||||
method: @"{{httpMethod}}"
|
||||
pathParams: pathParams
|
||||
queryParams: queryParams
|
||||
@ -175,8 +149,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513;
|
||||
if(handler) {
|
||||
handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error);
|
||||
}
|
||||
}
|
||||
];
|
||||
}];
|
||||
}
|
||||
|
||||
{{/operation}}
|
||||
|
@ -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;
|
||||
|
||||
|
@ -1,20 +1,18 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "{{classPrefix}}Object.h"
|
||||
#import "{{classPrefix}}ApiClient.h"
|
||||
#import "{{classPrefix}}ApiSessionManager.h"
|
||||
|
||||
{{>licenceInfo}}
|
||||
|
||||
@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) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key;
|
||||
-(NSString*) defaultHeaderForKey:(NSString*)key;
|
||||
|
||||
-(NSUInteger) requestQueueSize;
|
||||
|
||||
@end
|
||||
|
@ -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
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user