码迷,mamicode.com
首页 > Web开发 > 详细

第八篇、封装NSURLSession网络请求框架

时间:2016-11-11 23:35:50      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:push   enter   封装   sequence   instance   www   odi   val   gpe   

主要功能介绍:

  1.GET请求操作

  2.POST请求操作

 

1.处理params参数(例如拼接成:usename="123"&password="123")

#import <Foundation/Foundation.h>

@interface LYURLRequestSerialization : NSObject

+(NSString *)LYQueryStringFromParameters:(NSDictionary *)parameters;

@end

 

#import "LYURLRequestSerialization.h"

@interface LYURLRequestSerialization()

@property (readwrite, nonatomic, strong) id  value;
@property (readwrite, nonatomic, strong) id  field;


@end

@implementation LYURLRequestSerialization



- (id)initWithField:(id)field value:(id)value {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    self.field = field;
    self.value = value;
    
    return self;
}

#pragma mark -

FOUNDATION_EXPORT NSArray * LYQueryStringPairsFromDictionary(NSDictionary *dictionary);
FOUNDATION_EXPORT NSArray * LYQueryStringPairsFromKeyAndValue(NSString *key, id value);

+(NSString *)LYQueryStringFromParameters:(NSDictionary *)parameters {
    NSMutableArray *mutablePairs = [NSMutableArray array];
    for (LYURLRequestSerialization *pair in LYQueryStringPairsFromDictionary(parameters)) {
        
        [mutablePairs addObject:[pair URLEncodedStringValue]];
    }
    
    return [mutablePairs componentsJoinedByString:@"&"];
}



NSArray * LYQueryStringPairsFromDictionary(NSDictionary *dictionary) {
    return LYQueryStringPairsFromKeyAndValue(nil, dictionary);
}



NSArray * LYQueryStringPairsFromKeyAndValue(NSString *key, id value) {
    NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
    
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)];
    
    if ([value isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dictionary = value;
        for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
            id nestedValue = dictionary[nestedKey];
            if (nestedValue) {
                [mutableQueryStringComponents addObjectsFromArray:LYQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
            }
        }
    } else if ([value isKindOfClass:[NSArray class]]) {
        NSArray *array = value;
        for (id nestedValue in array) {
            [mutableQueryStringComponents addObjectsFromArray:LYQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
        }
    } else if ([value isKindOfClass:[NSSet class]]) {
        NSSet *set = value;
        for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
            [mutableQueryStringComponents addObjectsFromArray:LYQueryStringPairsFromKeyAndValue(key, obj)];
        }
    } else {
        [mutableQueryStringComponents addObject:[[LYURLRequestSerialization alloc] initWithField:key value:value]];
    }
    
    return mutableQueryStringComponents;
}


static NSString * LYPercentEscapedStringFromString(NSString *string) {
    static NSString * const kLYCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
    static NSString * const kLYCharactersSubDelimitersToEncode = @"!$&‘()*+,;=";
    
    NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
    [allowedCharacterSet removeCharactersInString:[kLYCharactersGeneralDelimitersToEncode stringByAppendingString:kLYCharactersSubDelimitersToEncode]];
    
    
    static NSUInteger const batchSize = 50;
    
    NSUInteger index = 0;
    NSMutableString *escaped = @"".mutableCopy;
    
    while (index < string.length) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wgnu"
        NSUInteger length = MIN(string.length - index, batchSize);
#pragma GCC diagnostic pop
        NSRange range = NSMakeRange(index, length);
        
        range = [string rangeOfComposedCharacterSequencesForRange:range];
        
        NSString *substring = [string substringWithRange:range];
        NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
        [escaped appendString:encoded];
        
        index += range.length;
    }
    
    return escaped;
}

- (NSString *)URLEncodedStringValue {
    if (!self.value || [self.value isEqual:[NSNull null]]) {
        return LYPercentEscapedStringFromString([self.field description]);
    } else {
        return [NSString stringWithFormat:@"%@=%@", LYPercentEscapedStringFromString([self.field description]), LYPercentEscapedStringFromString([self.value description])];
    }
}

@end

 

2.封装请求管理器

#import <Foundation/Foundation.h>

@interface LYHTTPRequestOperationManager : NSObject


-(void)driveTask:(nullable void(^)(NSData *__nullable data,NSURLResponse * __nullable response))success
         failure:(nullable void (^)(NSError *__nullable error))failure;


- (instancetype) initWithMethod:(NSString *)method URL:(NSString *)URL parameters:( id)parameters;


@end

 

#import "LYHTTPRequestOperationManager.h"
#import "LYURLRequestSerialization.h"

@interface LYHTTPRequestOperationManager()

@property(nonatomic,strong) NSString *URL;
@property(nonatomic,strong) NSString *method;
@property(nonatomic,strong) NSDictionary *parameters;
@property(nonatomic,strong) NSMutableURLRequest *request;
@property(nonatomic,strong) NSURLSession *session;
@property(nonatomic,strong) NSURLSessionDataTask *task;

@end

@implementation LYHTTPRequestOperationManager


- (instancetype)initWithMethod:(NSString *)method URL:(NSString *)URL parameters:(id)parameters
{
    self = [super init];
    if (!self) {
        return nil;
    }
    self.URL = URL;
    self.method = method;
    self.parameters = parameters;
    self.request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
    self.session = [NSURLSession sharedSession];
    return self;
}

-(void)test{
    NSLog(@"URL = %@",self.URL);
}

-(void)setRequest{
    if ([self.method isEqual:@"GET"]&&self.parameters.count>0) {
        
        self.request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[[self.URL stringByAppendingString:@"?"] stringByAppendingString: [LYURLRequestSerialization LYQueryStringFromParameters:self.parameters]]]];
    }
    self.request.HTTPMethod = self.method;
    
    if (self.parameters.count>0) {
        [self.request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    }
}


-(void)setBody{
    if (self.parameters.count>0&&![self.method isEqual:@"GET"]) {
       
        self.request.HTTPBody = [[LYURLRequestSerialization LYQueryStringFromParameters:self.parameters] dataUsingEncoding:NSUTF8StringEncoding];
    }
}


-(void)setTaskWithSuccess:(void(^)(NSData *__nullable data,NSURLResponse * __nullable response))success
                  failure:(void (^)(NSError *__nullable error))failure
{
    self.task = [self.session dataTaskWithRequest:self.request completionHandler:^(NSData * data,NSURLResponse *response,NSError *error){
                if (error) {
                    failure(error);
                }else{
                    if (success) {
                        success(data,response);
                    }
                }
            }];
    [self.task resume];
}


-(void)driveTask:(void(^)(NSData *__nullable data,NSURLResponse * __nullable response))success
         failure:(void (^)(NSError *__nullable error))failure
{
    [self setRequest];
    [self setBody];
    [self setTaskWithSuccess:success failure:failure];
}
@end

 

3.封装适配器

#import <Foundation/Foundation.h>

@interface LyNetWork : NSObject


+(void)requestWithMethod:(nullable NSString *)method
                     URL:(nullable NSString *)URL
                 success:(nullable void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
                 failure:(nullable void (^)(NSError *__nullable error))failure;


+( void)requestGetWithURL:(nullable NSString *)URL
                 success:(nullable void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
                  failure:(nullable void (^)(NSError *__nullable error))failure;


+(void)requestGetWithURL:(nullable NSString *)URL
              parameters:(nullable id) parameters
                 success:(nullable void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
                 failure:(nullable void (^)(NSError *__nullable error))failure;

+(void)requestPostWithURL:(nullable NSString *)URL
                  success:(nullable void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
                  failure:(nullable void (^)(NSError *__nullable error))failure;


+(void)requestPostWithURL:(nullable NSString *)URL
               parameters:(nullable id) parameters
                  success:(nullable void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
                  failure:(nullable void (^)(NSError *__nullable error))failure;



@end

 

#import "LyNetWork.h"
#import "LYURLRequestSerialization.h"
#import "LYHTTPRequestOperationManager.h"


@interface LyNetWork()



@end

@implementation LyNetWork


//+(void)requestMethod:(NSString *)method
//                 URL:(NSString *)URL
//          parameters:(id) parameters
//             success:(void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
//             failure:(void (^)(NSError *__nullable error))failure
//{
//    
//    LYHTTPRequestOperationManager *manange = [[LYHTTPRequestOperationManager alloc] initWithMethod:method URL:URL parameters:parameters];
//    [manange driveTask:success failure:failure];
//}

//不带parameters
+(void)requestWithMethod:(NSString *)method
                 URL:(NSString *)URL
             success:(void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
             failure:(void (^)(NSError *__nullable error))failure
{
    
    LYHTTPRequestOperationManager *manange = [[LYHTTPRequestOperationManager alloc] initWithMethod:method URL:URL parameters:nil];
    [manange driveTask:success failure:failure];
}


//GET不带parameters
+(void)requestGetWithURL:(NSString *)URL
             success:(void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
             failure:(void (^)(NSError *__nullable error))failure
{
    
    LYHTTPRequestOperationManager *manange = [[LYHTTPRequestOperationManager alloc] initWithMethod:@"GET" URL:URL parameters:nil];
    [manange driveTask:success failure:failure];
}
//GET带parameters
+(void)requestGetWithURL:(NSString *)URL
          parameters:(id) parameters
             success:(void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
             failure:(void (^)(NSError *__nullable error))failure
{
    
    LYHTTPRequestOperationManager *manange = [[LYHTTPRequestOperationManager alloc] initWithMethod:@"GET" URL:URL parameters:parameters];
    [manange driveTask:success failure:failure];
}



//POST不带parameters
+(void)requestPostWithURL:(NSString *)URL
                 success:(void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
                 failure:(void (^)(NSError *__nullable error))failure
{
    
    LYHTTPRequestOperationManager *manange = [[LYHTTPRequestOperationManager alloc] initWithMethod:@"POST" URL:URL parameters:nil];
    [manange driveTask:success failure:failure];
}
//POST带parameters
+(void)requestPostWithURL:(NSString *)URL
              parameters:(id) parameters
                 success:(void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
                 failure:(void (^)(NSError *__nullable error))failure
{
    
    LYHTTPRequestOperationManager *manange = [[LYHTTPRequestOperationManager alloc] initWithMethod:@"POST" URL:URL parameters:parameters];
    [manange driveTask:success failure:failure];
}



@end

 

4.使用示例

    NSString *postURL = @"http://cityuit.sinaapp.com/p.php";
    NSString *getURL= @"http://cityuit.sinaapp.com/1.php";
    
    id parmentersPost = @{
                      @"username":@"1",
                      @"password":@"1"
                      };
    id parmentersGet = @{
                      @"value":@"Lastday",
                          };

    
    
    [LyNetWork requestWithMethod:@"POST"
                             URL:@"http://cityuit.sinaapp.com/1.php?value=Lastday"
                         success:^(NSData *data,NSURLResponse *response){
                             NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                             NSLog(@"requestWithMethod = %@",string);
                         }
                         failure:^(NSError *error){
                             NSLog(@"====%@",error);
                         }];
    
    
    [LyNetWork requestPostWithURL:postURL
                       parameters:parmentersPost
                          success:^(NSData *data,NSURLResponse *response){
                              NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                              NSLog(@"requestPostWithURL(带参数) = %@",string);
                          }
                          failure:^(NSError *error){
                              
                          }];
    [LyNetWork requestPostWithURL:postURL
                          success:^(NSData *data,NSURLResponse *response){
                              NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                              NSLog(@"requestPostWithURL(不带参数) = %@",string);
                          }
                          failure:^(NSError *error){
                              
                          }];
    
    [LyNetWork requestGetWithURL:getURL
                       parameters:parmentersGet
                          success:^(NSData *data,NSURLResponse *response){
                              NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                              NSLog(@"requestGetWithURL(带参数) = %@",string);
                          }
                          failure:^(NSError *error){
                              
                          }];
    
    [LyNetWork requestGetWithURL:getURL
                          success:^(NSData *data,NSURLResponse *response){
                              NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                              NSLog(@"requestGetWithURL(不带参数) = %@",string);
                          }
                          failure:^(NSError *error){
                              
                          }];

 

第八篇、封装NSURLSession网络请求框架

标签:push   enter   封装   sequence   instance   www   odi   val   gpe   

原文地址:http://www.cnblogs.com/HJQ2016/p/6055617.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!