Conflicts:
	samples/client/petstore/objc/README.md
This commit is contained in:
wing328 2016-05-09 11:22:25 +08:00
commit 1a2bf79d51
4 changed files with 172 additions and 242 deletions

View File

@ -10,6 +10,30 @@ static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilitySta
static void (^reachabilityChangeBlock)(int); static void (^reachabilityChangeBlock)(int);
static NSDictionary * {{classPrefix}}__headerFieldsForResponse(NSURLResponse *response) {
if(![response isKindOfClass:[NSHTTPURLResponse class]]) {
return nil;
}
return ((NSHTTPURLResponse*)response).allHeaderFields;
}
static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) {
NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response);
if(!headers[@"Content-Disposition"]) {
return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
}
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?";
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *contentDispositionHeader = headers[@"Content-Disposition"];
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader
options:0
range:NSMakeRange(0, [contentDispositionHeader length])];
return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]];
}
@interface {{classPrefix}}ApiClient () @interface {{classPrefix}}ApiClient ()
@property (readwrite, nonatomic) NSDictionary *HTTPResponseHeaders; @property (readwrite, nonatomic) NSDictionary *HTTPResponseHeaders;
@ -96,14 +120,12 @@ static void (^reachabilityChangeBlock)(int);
va_end(args); va_end(args);
} }
- (void)logResponse:(AFHTTPRequestOperation *)operation - (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error {
forRequest:(NSURLRequest *)request
error:(NSError*)error {
NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\
"[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n",
[[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding],
operation.responseString]; responseObject];
{{classPrefix}}DebugLog(message); {{classPrefix}}DebugLog(message);
} }
@ -219,20 +241,14 @@ static void (^reachabilityChangeBlock)(int);
-(Boolean) executeRequestWithId:(NSNumber*) requestId { -(Boolean) executeRequestWithId:(NSNumber*) requestId {
NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) {
if ([obj intValue] == [requestId intValue]) { return [obj intValue] == [requestId intValue];
return YES;
}
else {
return NO;
}
}]; }];
if (matchingItems.count == 1) { if (matchingItems.count == 1) {
{{classPrefix}}DebugLog(@"removed request id %@", requestId); {{classPrefix}}DebugLog(@"removed request id %@", requestId);
[queuedRequests removeObject:requestId]; [queuedRequests removeObject:requestId];
return YES; return YES;
} } else {
else {
return NO; return NO;
} }
} }
@ -243,7 +259,7 @@ static void (^reachabilityChangeBlock)(int);
return reachabilityStatus; return reachabilityStatus;
} }
+(bool) getOfflineState { +(BOOL) getOfflineState {
return offlineState; return offlineState;
} }
@ -254,29 +270,8 @@ static void (^reachabilityChangeBlock)(int);
- (void) configureCacheReachibility { - (void) configureCacheReachibility {
[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
reachabilityStatus = status; reachabilityStatus = status;
switch (status) { {{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status));
case AFNetworkReachabilityStatusUnknown: [{{classPrefix}}ApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable];
{{classPrefix}}DebugLog(@"reachability changed to AFNetworkReachabilityStatusUnknown");
[{{classPrefix}}ApiClient setOfflineState:true];
break;
case AFNetworkReachabilityStatusNotReachable:
{{classPrefix}}DebugLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable");
[{{classPrefix}}ApiClient setOfflineState:true];
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
{{classPrefix}}DebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN");
[{{classPrefix}}ApiClient setOfflineState:false];
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
{{classPrefix}}DebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi");
[{{classPrefix}}ApiClient setOfflineState:false];
break;
default:
break;
}
// call the reachability block, if configured // call the reachability block, if configured
if (reachabilityChangeBlock != nil) { if (reachabilityChangeBlock != nil) {
@ -292,92 +287,60 @@ static void (^reachabilityChangeBlock)(int);
- (void) operationWithCompletionBlock: (NSURLRequest *)request - (void) operationWithCompletionBlock: (NSURLRequest *)request
requestId: (NSNumber *) requestId requestId: (NSNumber *) requestId
completionBlock: (void (^)(id, NSError *))completionBlock { completionBlock: (void (^)(id, NSError *))completionBlock {
AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request __weak __typeof(self)weakSelf = self;
success:^(AFHTTPRequestOperation *operation, id response) { NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if ([self executeRequestWithId:requestId]) { __strong __typeof(weakSelf)strongSelf = weakSelf;
[self logResponse:operation forRequest:request error:nil]; if (![strongSelf executeRequestWithId:requestId]) {
NSDictionary *responseHeaders = [[operation response] allHeaderFields]; return;
self.HTTPResponseHeaders = responseHeaders; }
completionBlock(response, nil); [strongSelf logResponse:response responseObject:responseObject request:request error:error];
} strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { if(!error) {
if ([self executeRequestWithId:requestId]) { completionBlock(responseObject, nil);
NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; return;
if (operation.responseObject) { }
// Add in the (parsed) response body. NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
userInfo[{{classPrefix}}ResponseObjectErrorKey] = operation.responseObject; if (responseObject) {
} // Add in the (parsed) response body.
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject;
[self logResponse:nil forRequest:request error:augmentedError]; }
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
NSDictionary *responseHeaders = [[operation response] allHeaderFields]; completionBlock(nil, augmentedError);
self.HTTPResponseHeaders = responseHeaders; }];
[op resume];
completionBlock(nil, augmentedError);
}
}];
[self.operationQueue addOperation:op];
} }
- (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request - (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request
requestId: (NSNumber *) requestId requestId: (NSNumber *) requestId
completionBlock: (void (^)(id, NSError *))completionBlock { completionBlock: (void (^)(id, NSError *))completionBlock {
AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request __weak __typeof(self)weakSelf = self;
success:^(AFHTTPRequestOperation *operation, id responseObject) { NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
{{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; __strong __typeof(weakSelf)strongSelf = weakSelf;
NSString *directory = nil; if (![strongSelf executeRequestWithId:requestId]) {
if (config.tempFolderPath) { return;
directory = config.tempFolderPath; }
} strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response);
else { [strongSelf logResponse:response responseObject:responseObject request:request error:error];
directory = NSTemporaryDirectory(); if(error) {
} NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
if (responseObject) {
userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject;
}
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
completionBlock(nil, augmentedError);
}
{{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig];
NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory();
NSString * filename = {{classPrefix}}__fileNameForResponse(response);
NSDictionary *headers = operation.response.allHeaderFields; NSString *filepath = [directory stringByAppendingPathComponent:filename];
NSString *filename = nil; NSURL *file = [NSURL fileURLWithPath:filepath];
if ([headers objectForKey:@"Content-Disposition"]) {
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; [responseObject writeToURL:file atomically:YES];
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *contentDispositionHeader = [headers objectForKey:@"Content-Disposition"];
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader
options:0
range:NSMakeRange(0, [contentDispositionHeader length])];
filename = [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]];
}
else {
filename = [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
}
NSString *filepath = [directory stringByAppendingPathComponent:filename]; completionBlock(file, nil);
NSURL *file = [NSURL fileURLWithPath:filepath]; }];
[op resume];
[operation.responseData writeToURL:file atomically:YES];
self.HTTPResponseHeaders = headers;
completionBlock(file, nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if ([self executeRequestWithId:requestId]) {
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
if (operation.responseObject) {
userInfo[{{classPrefix}}ResponseObjectErrorKey] = operation.responseObject;
}
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
[self logResponse:nil forRequest:request error:augmentedError];
NSDictionary *responseHeaders = [[operation response] allHeaderFields];
self.HTTPResponseHeaders = responseHeaders;
completionBlock(nil, augmentedError);
}
}];
[self.operationQueue addOperation:op];
} }
#pragma mark - Perform Request Methods #pragma mark - Perform Request Methods
@ -502,7 +465,7 @@ static void (^reachabilityChangeBlock)(int);
[request setHTTPShouldHandleCookies:NO]; [request setHTTPShouldHandleCookies:NO];
NSNumber* requestId = [{{classPrefix}}ApiClient queueRequest]; NSNumber* requestId = [{{classPrefix}}ApiClient queueRequest];
if ([responseType isEqualToString:@"NSURL*"]) { if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) {
[self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) {
completionBlock(data, error); completionBlock(data, error);
}]; }];

View File

@ -1,6 +1,6 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <ISO8601/ISO8601.h> #import <ISO8601/ISO8601.h>
#import <AFNetworking/AFHTTPRequestOperationManager.h> #import <AFNetworking.h>
#import "{{classPrefix}}JSONResponseSerializer.h" #import "{{classPrefix}}JSONResponseSerializer.h"
#import "{{classPrefix}}JSONRequestSerializer.h" #import "{{classPrefix}}JSONRequestSerializer.h"
#import "{{classPrefix}}QueryParamCollection.h" #import "{{classPrefix}}QueryParamCollection.h"
@ -30,7 +30,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
*/ */
#define {{classPrefix}}DebugLog(format, ...) [{{classPrefix}}ApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; #define {{classPrefix}}DebugLog(format, ...) [{{classPrefix}}ApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__];
@interface {{classPrefix}}ApiClient : AFHTTPRequestOperationManager @interface {{classPrefix}}ApiClient : AFHTTPSessionManager
@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; @property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
@property(nonatomic, assign) NSTimeInterval timeoutInterval; @property(nonatomic, assign) NSTimeInterval timeoutInterval;
@ -71,7 +71,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
* *
* @return The client offline state * @return The client offline state
*/ */
+(bool) getOfflineState; +(BOOL) getOfflineState;
/** /**
* Sets the client reachability, this may be overridden by the reachability manager if reachability changes * Sets the client reachability, this may be overridden by the reachability manager if reachability changes
@ -170,12 +170,14 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
/** /**
* Logs request and response * Logs request and response
* *
* @param operation AFHTTPRequestOperation for the HTTP request. * @param response NSURLResponse for the HTTP request.
* @param responseObject response object of the HTTP request.
* @param request The HTTP request. * @param request The HTTP request.
* @param error The error of the HTTP request. * @param error The error of the HTTP request.
*/ */
- (void)logResponse:(AFHTTPRequestOperation *)operation - (void)logResponse:(NSURLResponse *)response
forRequest:(NSURLRequest *)request responseObject:(id)responseObject
request:(NSURLRequest *)request
error:(NSError *)error; error:(NSError *)error;
/** /**

View File

@ -1,6 +1,6 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <ISO8601/ISO8601.h> #import <ISO8601/ISO8601.h>
#import <AFNetworking/AFHTTPRequestOperationManager.h> #import <AFNetworking.h>
#import "SWGJSONResponseSerializer.h" #import "SWGJSONResponseSerializer.h"
#import "SWGJSONRequestSerializer.h" #import "SWGJSONRequestSerializer.h"
#import "SWGQueryParamCollection.h" #import "SWGQueryParamCollection.h"
@ -34,7 +34,7 @@ extern NSString *const SWGResponseObjectErrorKey;
*/ */
#define SWGDebugLog(format, ...) [SWGApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; #define SWGDebugLog(format, ...) [SWGApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__];
@interface SWGApiClient : AFHTTPRequestOperationManager @interface SWGApiClient : AFHTTPSessionManager
@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; @property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
@property(nonatomic, assign) NSTimeInterval timeoutInterval; @property(nonatomic, assign) NSTimeInterval timeoutInterval;
@ -75,7 +75,7 @@ extern NSString *const SWGResponseObjectErrorKey;
* *
* @return The client offline state * @return The client offline state
*/ */
+(bool) getOfflineState; +(BOOL) getOfflineState;
/** /**
* Sets the client reachability, this may be overridden by the reachability manager if reachability changes * Sets the client reachability, this may be overridden by the reachability manager if reachability changes
@ -174,12 +174,14 @@ extern NSString *const SWGResponseObjectErrorKey;
/** /**
* Logs request and response * Logs request and response
* *
* @param operation AFHTTPRequestOperation for the HTTP request. * @param response NSURLResponse for the HTTP request.
* @param responseObject response object of the HTTP request.
* @param request The HTTP request. * @param request The HTTP request.
* @param error The error of the HTTP request. * @param error The error of the HTTP request.
*/ */
- (void)logResponse:(AFHTTPRequestOperation *)operation - (void)logResponse:(NSURLResponse *)response
forRequest:(NSURLRequest *)request responseObject:(id)responseObject
request:(NSURLRequest *)request
error:(NSError *)error; error:(NSError *)error;
/** /**

View File

@ -10,6 +10,30 @@ static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilitySta
static void (^reachabilityChangeBlock)(int); static void (^reachabilityChangeBlock)(int);
static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) {
if(![response isKindOfClass:[NSHTTPURLResponse class]]) {
return nil;
}
return ((NSHTTPURLResponse*)response).allHeaderFields;
}
static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
NSDictionary * headers = SWG__headerFieldsForResponse(response);
if(!headers[@"Content-Disposition"]) {
return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
}
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?";
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *contentDispositionHeader = headers[@"Content-Disposition"];
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader
options:0
range:NSMakeRange(0, [contentDispositionHeader length])];
return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]];
}
@interface SWGApiClient () @interface SWGApiClient ()
@property (readwrite, nonatomic) NSDictionary *HTTPResponseHeaders; @property (readwrite, nonatomic) NSDictionary *HTTPResponseHeaders;
@ -96,14 +120,12 @@ static void (^reachabilityChangeBlock)(int);
va_end(args); va_end(args);
} }
- (void)logResponse:(AFHTTPRequestOperation *)operation - (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error {
forRequest:(NSURLRequest *)request
error:(NSError*)error {
NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\
"[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n",
[[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding],
operation.responseString]; responseObject];
SWGDebugLog(message); SWGDebugLog(message);
} }
@ -219,20 +241,14 @@ static void (^reachabilityChangeBlock)(int);
-(Boolean) executeRequestWithId:(NSNumber*) requestId { -(Boolean) executeRequestWithId:(NSNumber*) requestId {
NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) {
if ([obj intValue] == [requestId intValue]) { return [obj intValue] == [requestId intValue];
return YES;
}
else {
return NO;
}
}]; }];
if (matchingItems.count == 1) { if (matchingItems.count == 1) {
SWGDebugLog(@"removed request id %@", requestId); SWGDebugLog(@"removed request id %@", requestId);
[queuedRequests removeObject:requestId]; [queuedRequests removeObject:requestId];
return YES; return YES;
} } else {
else {
return NO; return NO;
} }
} }
@ -243,7 +259,7 @@ static void (^reachabilityChangeBlock)(int);
return reachabilityStatus; return reachabilityStatus;
} }
+(bool) getOfflineState { +(BOOL) getOfflineState {
return offlineState; return offlineState;
} }
@ -254,29 +270,8 @@ static void (^reachabilityChangeBlock)(int);
- (void) configureCacheReachibility { - (void) configureCacheReachibility {
[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
reachabilityStatus = status; reachabilityStatus = status;
switch (status) { SWGDebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status));
case AFNetworkReachabilityStatusUnknown: [SWGApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable];
SWGDebugLog(@"reachability changed to AFNetworkReachabilityStatusUnknown");
[SWGApiClient setOfflineState:true];
break;
case AFNetworkReachabilityStatusNotReachable:
SWGDebugLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable");
[SWGApiClient setOfflineState:true];
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
SWGDebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN");
[SWGApiClient setOfflineState:false];
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
SWGDebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi");
[SWGApiClient setOfflineState:false];
break;
default:
break;
}
// call the reachability block, if configured // call the reachability block, if configured
if (reachabilityChangeBlock != nil) { if (reachabilityChangeBlock != nil) {
@ -292,92 +287,60 @@ static void (^reachabilityChangeBlock)(int);
- (void) operationWithCompletionBlock: (NSURLRequest *)request - (void) operationWithCompletionBlock: (NSURLRequest *)request
requestId: (NSNumber *) requestId requestId: (NSNumber *) requestId
completionBlock: (void (^)(id, NSError *))completionBlock { completionBlock: (void (^)(id, NSError *))completionBlock {
AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request __weak __typeof(self)weakSelf = self;
success:^(AFHTTPRequestOperation *operation, id response) { NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if ([self executeRequestWithId:requestId]) { __strong __typeof(weakSelf)strongSelf = weakSelf;
[self logResponse:operation forRequest:request error:nil]; if (![strongSelf executeRequestWithId:requestId]) {
NSDictionary *responseHeaders = [[operation response] allHeaderFields]; return;
self.HTTPResponseHeaders = responseHeaders; }
completionBlock(response, nil); [strongSelf logResponse:response responseObject:responseObject request:request error:error];
} strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { if(!error) {
if ([self executeRequestWithId:requestId]) { completionBlock(responseObject, nil);
NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; return;
if (operation.responseObject) { }
// Add in the (parsed) response body. NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
userInfo[SWGResponseObjectErrorKey] = operation.responseObject; if (responseObject) {
} // Add in the (parsed) response body.
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; userInfo[SWGResponseObjectErrorKey] = responseObject;
[self logResponse:nil forRequest:request error:augmentedError]; }
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
NSDictionary *responseHeaders = [[operation response] allHeaderFields]; completionBlock(nil, augmentedError);
self.HTTPResponseHeaders = responseHeaders; }];
[op resume];
completionBlock(nil, augmentedError);
}
}];
[self.operationQueue addOperation:op];
} }
- (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request - (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request
requestId: (NSNumber *) requestId requestId: (NSNumber *) requestId
completionBlock: (void (^)(id, NSError *))completionBlock { completionBlock: (void (^)(id, NSError *))completionBlock {
AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request __weak __typeof(self)weakSelf = self;
success:^(AFHTTPRequestOperation *operation, id responseObject) { NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
SWGConfiguration *config = [SWGConfiguration sharedConfig]; __strong __typeof(weakSelf)strongSelf = weakSelf;
NSString *directory = nil; if (![strongSelf executeRequestWithId:requestId]) {
if (config.tempFolderPath) { return;
directory = config.tempFolderPath; }
} strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response);
else { [strongSelf logResponse:response responseObject:responseObject request:request error:error];
directory = NSTemporaryDirectory(); if(error) {
} NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
if (responseObject) {
userInfo[SWGResponseObjectErrorKey] = responseObject;
}
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
completionBlock(nil, augmentedError);
}
SWGConfiguration *config = [SWGConfiguration sharedConfig];
NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory();
NSString * filename = SWG__fileNameForResponse(response);
NSDictionary *headers = operation.response.allHeaderFields; NSString *filepath = [directory stringByAppendingPathComponent:filename];
NSString *filename = nil; NSURL *file = [NSURL fileURLWithPath:filepath];
if ([headers objectForKey:@"Content-Disposition"]) {
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; [responseObject writeToURL:file atomically:YES];
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *contentDispositionHeader = [headers objectForKey:@"Content-Disposition"];
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader
options:0
range:NSMakeRange(0, [contentDispositionHeader length])];
filename = [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]];
}
else {
filename = [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
}
NSString *filepath = [directory stringByAppendingPathComponent:filename]; completionBlock(file, nil);
NSURL *file = [NSURL fileURLWithPath:filepath]; }];
[op resume];
[operation.responseData writeToURL:file atomically:YES];
self.HTTPResponseHeaders = headers;
completionBlock(file, nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if ([self executeRequestWithId:requestId]) {
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
if (operation.responseObject) {
userInfo[SWGResponseObjectErrorKey] = operation.responseObject;
}
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
[self logResponse:nil forRequest:request error:augmentedError];
NSDictionary *responseHeaders = [[operation response] allHeaderFields];
self.HTTPResponseHeaders = responseHeaders;
completionBlock(nil, augmentedError);
}
}];
[self.operationQueue addOperation:op];
} }
#pragma mark - Perform Request Methods #pragma mark - Perform Request Methods
@ -502,7 +465,7 @@ static void (^reachabilityChangeBlock)(int);
[request setHTTPShouldHandleCookies:NO]; [request setHTTPShouldHandleCookies:NO];
NSNumber* requestId = [SWGApiClient queueRequest]; NSNumber* requestId = [SWGApiClient queueRequest];
if ([responseType isEqualToString:@"NSURL*"]) { if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) {
[self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) {
completionBlock(data, error); completionBlock(data, error);
}]; }];