Removing categories on NSData and NSString, moving them to static functions in AFRestClient

Removing Gzip functionality, which will be extracted into its own library
This commit is contained in:
Mattt Thompson 2011-09-21 11:36:39 -05:00
parent 2f7f527d9c
commit ca02e02b11
7 changed files with 48 additions and 265 deletions

View file

@ -24,11 +24,11 @@
#import "AFHTTPRequestOperation.h"
#import "NSMutableURLRequest+AFNetworking.h"
#import "NSString+AFNetworking.h"
@interface AFRestClient : NSObject {
@private
NSURL *_baseURL;
NSStringEncoding _stringEncoding;
NSMutableDictionary *_defaultHeaders;
NSOperationQueue *_operationQueue;
}
@ -38,6 +38,10 @@
*/
@property (readonly, nonatomic, retain) NSURL *baseURL;
@property (nonatomic, assign) NSStringEncoding stringEncoding;
@property (readonly, nonatomic, retain) NSOperationQueue *operationQueue;;
///--------------------------------
/// @name Initializing REST Clients
///--------------------------------

View file

@ -23,9 +23,40 @@
#import "AFRestClient.h"
#import "AFJSONRequestOperation.h"
#import "NSData+AFNetworking.h"
static NSString * AFBase64EncodedStringFromString(NSString *string) {
NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string length]];
NSUInteger length = [data length];
NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t *input = (uint8_t *)[data bytes];
uint8_t *output = (uint8_t *)[mutableData mutableBytes];
for (NSUInteger i = 0; i < length; i += 3) {
NSUInteger value = 0;
for (NSUInteger j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
static char const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static NSStringEncoding const kAFRestClientStringEncoding = NSUTF8StringEncoding;
NSInteger idx = (i / 3) * 4;
output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F];
output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F];
output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '=';
output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '=';
}
return [[[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding] autorelease];
}
static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
static NSString * const kAFLegalCharactersToBeEscaped = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\|~ ";
return [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, (CFStringRef)kAFLegalCharactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding)) autorelease];
}
@interface AFRestClient ()
@property (readwrite, nonatomic, retain) NSURL *baseURL;
@ -35,6 +66,7 @@ static NSStringEncoding const kAFRestClientStringEncoding = NSUTF8StringEncoding
@implementation AFRestClient
@synthesize baseURL = _baseURL;
@synthesize stringEncoding = _stringEncoding;
@synthesize defaultHeaders = _defaultHeaders;
@synthesize operationQueue = _operationQueue;
@ -46,8 +78,7 @@ static NSStringEncoding const kAFRestClientStringEncoding = NSUTF8StringEncoding
self.baseURL = url;
self.operationQueue = [[[NSOperationQueue alloc] init] autorelease];
[self.operationQueue setMaxConcurrentOperationCount:2];
self.stringEncoding = NSUTF8StringEncoding;
self.defaultHeaders = [NSMutableDictionary dictionary];
@ -64,6 +95,9 @@ static NSStringEncoding const kAFRestClientStringEncoding = NSUTF8StringEncoding
// User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
[self setDefaultHeader:@"User-Agent" value:[NSString stringWithFormat:@"%@/%@ (%@, %@ %@, %@, Scale/%f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey], @"unknown", [[UIDevice currentDevice] systemName], [[UIDevice currentDevice] systemVersion], [[UIDevice currentDevice] model], ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] ? [[UIScreen mainScreen] scale] : 1.0)]];
self.operationQueue = [[[NSOperationQueue alloc] init] autorelease];
[self.operationQueue setMaxConcurrentOperationCount:2];
return self;
}
@ -83,9 +117,8 @@ static NSStringEncoding const kAFRestClientStringEncoding = NSUTF8StringEncoding
}
- (void)setAuthorizationHeaderWithUsername:(NSString *)username password:(NSString *)password {
NSString *authHeader = [NSString stringWithFormat:@"%@:%@", username, password];
NSString *encodedAuthHeader = [[NSData dataWithBytes:[authHeader UTF8String] length:[authHeader length]] base64EncodedString];
[self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"Basic %@", encodedAuthHeader]];
NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password];
[self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)]];
}
- (void)setAuthorizationHeaderWithToken:(NSString *)token {
@ -106,7 +139,7 @@ static NSStringEncoding const kAFRestClientStringEncoding = NSUTF8StringEncoding
if (parameters) {
NSMutableArray *mutableParameterComponents = [NSMutableArray array];
for (id key in [parameters allKeys]) {
NSString *component = [NSString stringWithFormat:@"%@=%@", [[key description] urlEncodedStringWithEncoding:kAFRestClientStringEncoding], [[[parameters valueForKey:key] description] urlEncodedStringWithEncoding:kAFRestClientStringEncoding]];
NSString *component = [NSString stringWithFormat:@"%@=%@", AFURLEncodedStringFromStringWithEncoding([key description], self.stringEncoding), AFURLEncodedStringFromStringWithEncoding([[parameters valueForKey:key] description], self.stringEncoding)];
[mutableParameterComponents addObject:component];
}
NSString *queryString = [mutableParameterComponents componentsJoinedByString:@"&"];
@ -114,9 +147,9 @@ static NSStringEncoding const kAFRestClientStringEncoding = NSUTF8StringEncoding
if ([method isEqualToString:@"GET"]) {
url = [NSURL URLWithString:[[url absoluteString] stringByAppendingFormat:[path rangeOfString:@"?"].location == NSNotFound ? @"?%@" : @"&%@", queryString]];
} else {
NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(kAFRestClientStringEncoding));
NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
[headers setObject:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forKey:@"Content-Type"];
[request setHTTPBody:[queryString dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:[queryString dataUsingEncoding:self.stringEncoding]];
}
}

View file

@ -1,33 +0,0 @@
// NSData+AFNetworking.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
extern NSString * const AFZlibErrorDomain;
@interface NSData (AFNetworking)
- (NSString *)base64EncodedString;
- (NSData *)dataByGZipCompressingWithError:(NSError **)error;
- (NSData *)dataByGZipDecompressingDataWithError:(NSError **)error;
@end

View file

@ -1,141 +0,0 @@
// NSData+AFNetworking.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "NSData+AFNetworking.h"
#import "AFHTTPRequestOperation.h"
#import <zlib.h>
NSString * const AFZlibErrorDomain = @"com.alamofire.networking.zlib.error";
static char Base64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
#pragma mark -
@implementation NSData (AFNetworking)
- (NSString *)base64EncodedString {
NSUInteger length = [self length];
NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t *input = (uint8_t *)[self bytes];
uint8_t *output = (uint8_t *)[mutableData mutableBytes];
for (NSUInteger i = 0; i < length; i += 3) {
NSUInteger value = 0;
for (NSUInteger j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
NSInteger idx = (i / 3) * 4;
output[idx + 0] = Base64EncodingTable[(value >> 18) & 0x3F];
output[idx + 1] = Base64EncodingTable[(value >> 12) & 0x3F];
output[idx + 2] = (i + 1) < length ? Base64EncodingTable[(value >> 6) & 0x3F] : '=';
output[idx + 3] = (i + 2) < length ? Base64EncodingTable[(value >> 0) & 0x3F] : '=';
}
return [[[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding] autorelease];
}
- (NSData *)dataByGZipCompressingWithError:(NSError **)error {
if ([self length] == 0) {
return self;
}
z_stream zStream;
zStream.zalloc = Z_NULL;
zStream.zfree = Z_NULL;
zStream.opaque = Z_NULL;
zStream.next_in = (Bytef *)[self bytes];
zStream.avail_in = [self length];
zStream.total_out = 0;
if (deflateInit(&zStream, Z_DEFAULT_COMPRESSION) != Z_OK) {
return nil;
}
NSUInteger compressionChunkSize = 16384; // 16Kb
NSMutableData *compressedData = [NSMutableData dataWithLength:compressionChunkSize];
do {
if (zStream.total_out >= [compressedData length]) {
[compressedData increaseLengthBy:compressionChunkSize];
}
zStream.next_out = [compressedData mutableBytes] + zStream.total_out;
zStream.avail_out = [compressedData length] - zStream.total_out;
deflate(&zStream, Z_FINISH);
} while (zStream.avail_out == 0);
deflateEnd(&zStream);
[compressedData setLength:zStream.total_out];
return [NSData dataWithData:compressedData];
}
- (NSData *)dataByGZipDecompressingDataWithError:(NSError **)error {
z_stream zStream;
zStream.zalloc = Z_NULL;
zStream.zfree = Z_NULL;
zStream.next_in = (Bytef *)[self bytes];
zStream.avail_in = [self length];
zStream.avail_out = 0;
zStream.total_out = 0;
NSUInteger estimatedLength = [self length] / 2;
NSMutableData *decompressedData = [NSMutableData dataWithLength:estimatedLength];
do {
if (zStream.total_out >= [decompressedData length]) {
[decompressedData increaseLengthBy:estimatedLength / 2];
}
zStream.next_out = [decompressedData mutableBytes] + zStream.total_out;
zStream.avail_out = [decompressedData length] - zStream.total_out;
int status = inflate(&zStream, Z_FINISH);
if (status == Z_STREAM_END) {
break;
} else if (status != Z_OK) {
if (error) {
*error = [NSError errorWithDomain:AFZlibErrorDomain code:status userInfo:nil];
}
return nil;
}
} while (zStream.avail_out == 0);
[decompressedData setLength:zStream.total_out];
return [NSData dataWithData:decompressedData];
}
@end

View file

@ -1,30 +0,0 @@
// NSString+AFNetworking.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
@interface NSString (AFNetworking)
- (NSString *)urlEncodedString;
- (NSString *)urlEncodedStringWithEncoding:(NSStringEncoding)encoding;
@end

View file

@ -1,38 +0,0 @@
// NSString+AFNetworking.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "NSString+AFNetworking.h"
@implementation NSString (AFNetworking)
- (NSString*)urlEncodedString {
return [self urlEncodedStringWithEncoding:NSUTF8StringEncoding];
}
// See http://github.com/pokeb/asi-http-request/raw/master/Classes/ASIFormDataRequest.m
- (NSString *)urlEncodedStringWithEncoding:(NSStringEncoding)encoding {
NSString *urlEncodedString = [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, (CFStringRef)@":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`", CFStringConvertNSStringEncodingToEncoding(encoding)) autorelease];
return urlEncodedString ? urlEncodedString : @"";
}
@end

View file

@ -7,9 +7,7 @@
objects = {
/* Begin PBXBuildFile section */
F85CE2D413EC478F00BFAE01 /* NSString+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F85CE2D313EC478F00BFAE01 /* NSString+AFNetworking.m */; };
F85CE2DC13EC4A4200BFAE01 /* NSMutableURLRequest+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F85CE2DB13EC4A4200BFAE01 /* NSMutableURLRequest+AFNetworking.m */; };
F85CE55513EC759200BFAE01 /* NSData+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F85CE55413EC759200BFAE01 /* NSData+AFNetworking.m */; };
F874B5D913E0AA6500B28E3E /* AFHTTPRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */; };
F874B5DA13E0AA6500B28E3E /* AFImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5CA13E0AA6500B28E3E /* AFImageCache.m */; };
F874B5DB13E0AA6500B28E3E /* AFImageRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5CB13E0AA6500B28E3E /* AFImageRequestOperation.m */; };
@ -36,12 +34,8 @@
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
F85CE2D213EC478F00BFAE01 /* NSString+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSString+AFNetworking.h"; path = "../AFNetworking/NSString+AFNetworking.h"; sourceTree = "<group>"; };
F85CE2D313EC478F00BFAE01 /* NSString+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSString+AFNetworking.m"; path = "../AFNetworking/NSString+AFNetworking.m"; sourceTree = "<group>"; };
F85CE2DA13EC4A4200BFAE01 /* NSMutableURLRequest+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSMutableURLRequest+AFNetworking.h"; path = "../AFNetworking/NSMutableURLRequest+AFNetworking.h"; sourceTree = "<group>"; };
F85CE2DB13EC4A4200BFAE01 /* NSMutableURLRequest+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSMutableURLRequest+AFNetworking.m"; path = "../AFNetworking/NSMutableURLRequest+AFNetworking.m"; sourceTree = "<group>"; };
F85CE55313EC759100BFAE01 /* NSData+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSData+AFNetworking.h"; path = "../AFNetworking/NSData+AFNetworking.h"; sourceTree = "<group>"; };
F85CE55413EC759200BFAE01 /* NSData+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSData+AFNetworking.m"; path = "../AFNetworking/NSData+AFNetworking.m"; sourceTree = "<group>"; };
F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPRequestOperation.m; path = ../AFNetworking/AFHTTPRequestOperation.m; sourceTree = "<group>"; };
F874B5CA13E0AA6500B28E3E /* AFImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageCache.m; path = ../AFNetworking/AFImageCache.m; sourceTree = "<group>"; };
F874B5CB13E0AA6500B28E3E /* AFImageRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageRequestOperation.m; path = ../AFNetworking/AFImageRequestOperation.m; sourceTree = "<group>"; };
@ -109,14 +103,10 @@
children = (
F85CE2DA13EC4A4200BFAE01 /* NSMutableURLRequest+AFNetworking.h */,
F85CE2DB13EC4A4200BFAE01 /* NSMutableURLRequest+AFNetworking.m */,
F85CE2D213EC478F00BFAE01 /* NSString+AFNetworking.h */,
F85CE2D313EC478F00BFAE01 /* NSString+AFNetworking.m */,
F874B5D713E0AA6500B28E3E /* UIImage+AFNetworking.h */,
F874B5CF13E0AA6500B28E3E /* UIImage+AFNetworking.m */,
F874B5D813E0AA6500B28E3E /* UIImageView+AFNetworking.h */,
F874B5D013E0AA6500B28E3E /* UIImageView+AFNetworking.m */,
F85CE55313EC759100BFAE01 /* NSData+AFNetworking.h */,
F85CE55413EC759200BFAE01 /* NSData+AFNetworking.m */,
);
name = Categories;
sourceTree = "<group>";
@ -358,9 +348,7 @@
F874B5DE13E0AA6500B28E3E /* AFRestClient.m in Sources */,
F874B5DF13E0AA6500B28E3E /* UIImage+AFNetworking.m in Sources */,
F874B5E013E0AA6500B28E3E /* UIImageView+AFNetworking.m in Sources */,
F85CE2D413EC478F00BFAE01 /* NSString+AFNetworking.m in Sources */,
F85CE2DC13EC4A4200BFAE01 /* NSMutableURLRequest+AFNetworking.m in Sources */,
F85CE55513EC759200BFAE01 /* NSData+AFNetworking.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};