[セットトップ]カスタムネットワーク要求エンジン


//
//  MQLNormalDownloaler.h
//
//  Created by MQL
//

#import <Foundation/Foundation.h>

@interface MQLNormalDownloaler : NSObject

/**
 *   
 *
 *  @param URL              
 *  @param parameters       nil, HTTP body
 *  @param timeoutInterval  
 *  @param success          block
 *  @param failure          block
 *
 *  @return  
 */
+ (id)downloadWithURL:(NSURL *)URL
           parameters:(NSDictionary *)parameters
      timeoutInterval:(NSTimeInterval)timeoutInterval
              success:(void (^)(id responseData))success
              failure:(void (^)(NSError *error))failure;

/**
 *   
 */
- (void)start;

/**
 *   
 */
- (void)cancel;


@end


//
//  MQLNormalDownloaler.m
//
//  Created by MQL
//

#import "MQLNormalDownloaler.h"

typedef void (^completionBlock)();

@interface MQLNormalDownloaler ()
@property (nonatomic, readwrite, retain) NSURL *URL;
@property(nonatomic, readwrite, retain) NSMutableData* responseData;

@property(nonatomic, readwrite, retain) NSURLConnection* connection;
@property(nonatomic, readwrite, retain) NSDictionary *parameters;
@property(nonatomic, readwrite, assign) NSTimeInterval timeoutInterval;
@property(nonatomic, readwrite, copy) completionBlock completionBlock;
@property(nonatomic, readwrite, retain) NSError *error;

/**
 *   、 block
 *
 *  @param success  block
 *  @param failure  block
 */
- (void)setCompletionBlockWithSuccess:(void (^)(id responseData))success
                              failure:(void (^)(NSError *error))failure;

@end

@implementation MQLNormalDownloaler

/**
 *   、 block
 *
 *  @param success  block
 *  @param failure  block
 */
- (void)setCompletionBlockWithSuccess:(void (^)(id responseData))success
                              failure:(void (^)(NSError *error))failure
{
    __weak typeof(self) weakSelf = self;
    self.completionBlock = ^ {
        if (weakSelf.error) {
            if (failure) {
                failure(weakSelf.error);
            }
        } else {
            if (success) {
                success(weakSelf.responseData);
            }
        }
    };
}


/**
 *   
 *
 *  @param URL              
 *  @param parameters       nil, HTTP body
 *  @param timeoutInterval  
 *  @param success          block
 *  @param failure          block
 *
 *  @return  
 */
+ (id)downloadWithURL:(NSURL *)URL
           parameters:(NSDictionary *)parameters
      timeoutInterval:(NSTimeInterval)timeoutInterval
              success:(void (^)(id responseData))success
              failure:(void (^)(NSError *error))failure
{
    MQLNormalDownloaler *downloader = [[MQLNormalDownloaler alloc] init];
    downloader.URL = URL;
    downloader.parameters = parameters;
    downloader.timeoutInterval = timeoutInterval;
    [downloader setCompletionBlockWithSuccess:success failure:failure];
    
    //Start on main thread
    [downloader performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:YES];
    
    return downloader;
}

/**
 *   
 */
- (void)start
{
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:self.URL
                                                                cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                            timeoutInterval:self.timeoutInterval];
    if (self.parameters == nil) {
        
        [request setHTTPMethod: @"GET"];
        
    }else{
        
        [request setHTTPMethod: @"POST"];
        
        [self.parameters enumerateKeysAndObjectsUsingBlock:^(id nestedKey, id nestedValue, BOOL *stop){
            
            NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
            NSString *stringComponent = [NSString stringWithFormat:@"%@=%@", nestedKey, [nestedValue description]];
            [mutableQueryStringComponents addObject:stringComponent];
            NSString *queryString = [mutableQueryStringComponents componentsJoinedByString:@"&"];
            [request setHTTPBody:[queryString dataUsingEncoding:NSUTF8StringEncoding]];
            
        }];
        
    }
    
    
    self.connection =[[NSURLConnection alloc] initWithRequest:request
                                                     delegate:self
                                             startImmediately:NO];
    [self.connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    [self.connection start];
}

/**
 *   
 */
- (void)cancel
{
    if (self.connection)
    {
        [self.connection cancel];
        self.connection = nil;
    }
}

#pragma mark - NSURLConnection Delegate
- (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)response
{
    if (![response respondsToSelector:@selector(statusCode)] || [((NSHTTPURLResponse *)response) statusCode] < 400)
    {
        NSUInteger expectedSize = response.expectedContentLength > 0 ? (NSUInteger)response.expectedContentLength : 0;
        self.responseData = [[NSMutableData alloc] initWithCapacity:expectedSize];
    }
    else
    {
        [aConnection cancel];
        
        NSError *error = [[NSError alloc] initWithDomain:NSURLErrorDomain
                                                    code:[((NSHTTPURLResponse *)response) statusCode]
                                                userInfo:nil];
        self.error = error;
        self.connection = nil;
        self.responseData = nil;
        self.completionBlock();
    }
}

- (void)connection:(NSURLConnection *)aConnection didReceiveData:(NSData *)data
{
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection
{
    self.connection = nil;
    self.completionBlock();
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    self.connection = nil;
    self.responseData = nil;
    self.error = error;
    self.completionBlock();
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
    return nil;
}

@end