AFCSVRequestOperation, for requesting and parsing CSV with AFNetworking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// AFCSVRequestOperation.h | |
// | |
// Created by Jesse Crocker <datamongers.net> on 12/30/2012 | |
// Based on AFJSONRequestOperation.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> | |
#import "AFHTTPRequestOperation.h" | |
/** | |
`AFCSVRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with CSV response data. | |
## Acceptable Content Types | |
By default, `AFCSVRequestOperation` accepts the following MIME types, which includes the official standard, `text/csv`, as well as other commonly-used types: | |
- `application/csv` | |
*/ | |
@interface AFCSVRequestOperation : AFHTTPRequestOperation | |
///---------------------------- | |
/// @name Getting Response Data | |
///---------------------------- | |
/** | |
A CSV array constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error. | |
*/ | |
@property (readonly, nonatomic, strong) NSArray *responseCSV; | |
/** | |
The seperator between items, defaults to ",". | |
*/ | |
@property (nonatomic, strong) NSString *seperator; | |
@property (nonatomic, assign) BOOL removeSpaces; | |
///---------------------------------- | |
/// @name Creating Request Operations | |
///---------------------------------- | |
/** | |
Creates and returns an `AFCSVRequestOperation` object and sets the specified success and failure callbacks. | |
@param urlRequest The request object to be loaded asynchronously during execution of the operation | |
@param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the CSV object created from the response data of request. | |
@param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as CSV. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred. | |
@return A new CSV request operation | |
*/ | |
+ (AFCSVRequestOperation *)CSVRequestOperationWithRequest:(NSURLRequest *)urlRequest | |
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSArray *CSV))success | |
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSArray *CSV))failure; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// AFCSVRequestOperation.m | |
// | |
// Created by Jesse Crocker <datamongers.net> on 12/30/2012 | |
// Based on AFJSONRequestOperation.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 "AFCSVRequestOperation.h" | |
static dispatch_queue_t af_csv_request_operation_processing_queue; | |
static dispatch_queue_t csv_request_operation_processing_queue() { | |
if (af_csv_request_operation_processing_queue == NULL) { | |
af_csv_request_operation_processing_queue = dispatch_queue_create("net.datamongers.json-request.processing", 0); | |
} | |
return af_csv_request_operation_processing_queue; | |
} | |
@interface AFCSVRequestOperation () | |
@property (readwrite, nonatomic, strong) NSArray *responseCSV; | |
@property (readwrite, nonatomic, strong) NSError *CSVError; | |
@end | |
@implementation AFCSVRequestOperation | |
@synthesize responseCSV = _responseCSV; | |
@synthesize CSVError = _CSVError; | |
@synthesize removeSpaces; | |
+ (AFCSVRequestOperation *)CSVRequestOperationWithRequest:(NSURLRequest *)urlRequest | |
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSArray *CSV))success | |
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSArray *CSV))failure | |
{ | |
AFCSVRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest]; | |
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { | |
if (success) { | |
success(operation.request, operation.response, responseObject); | |
} | |
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { | |
if (failure) { | |
failure(operation.request, operation.response, error, [(AFCSVRequestOperation *)operation responseCSV]); | |
} | |
}]; | |
return requestOperation; | |
} | |
- (NSArray*)responseCSV { | |
if (!_responseCSV && [self.responseString length] > 0 && [self isFinished] && !self.CSVError) { | |
NSError *error = nil; | |
NSString *thisSeperator; | |
if(self.seperator.length) { | |
thisSeperator = self.seperator; | |
} else { | |
thisSeperator = @","; | |
} | |
if ([self.responseString length] == 0) { | |
self.responseCSV = nil; | |
} else { | |
NSMutableArray *lines = [NSMutableArray array]; | |
[self.responseString enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) { | |
NSArray *thisLine; | |
if(removeSpaces){ | |
NSMutableString *mutableLine = line.mutableCopy; | |
[mutableLine replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [mutableLine length])]; | |
[mutableLine replaceOccurrencesOfString:@"\t" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [mutableLine length])]; | |
thisLine = [mutableLine componentsSeparatedByString:thisSeperator]; | |
}else { | |
thisLine = [line componentsSeparatedByString:thisSeperator]; | |
} | |
[lines addObject:thisLine]; | |
}]; | |
self.responseCSV = lines; | |
} | |
self.CSVError = error; | |
} | |
return _responseCSV; | |
} | |
- (NSError *)error { | |
if (_CSVError) { | |
return _CSVError; | |
} else { | |
return [super error]; | |
} | |
} | |
#pragma mark - AFHTTPRequestOperation | |
+ (NSSet *)acceptableContentTypes { | |
return [NSSet setWithObjects:@"text/csv", @"application/csv", nil]; | |
} | |
+ (BOOL)canProcessRequest:(NSURLRequest *)request { | |
return [[[request URL] pathExtension] isEqualToString:@"csv"] || [super canProcessRequest:request]; | |
} | |
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success | |
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure | |
{ | |
#pragma clang diagnostic push | |
#pragma clang diagnostic ignored "-Warc-retain-cycles" | |
self.completionBlock = ^ { | |
if ([self isCancelled]) { | |
return; | |
} | |
if (self.error) { | |
if (failure) { | |
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ | |
failure(self, self.error); | |
}); | |
} | |
} else { | |
dispatch_async(csv_request_operation_processing_queue(), ^{ | |
NSArray *csv = self.responseCSV; | |
if (self.CSVError) { | |
if (failure) { | |
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ | |
failure(self, self.error); | |
}); | |
} | |
} else { | |
if (success) { | |
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ | |
success(self, csv); | |
}); | |
} | |
} | |
}); | |
} | |
}; | |
#pragma clang diagnostic pop | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment