网络请求

#import <Foundation/Foundation.h>

 

 

typedef void(^Finish)(NSData *data);//请求成功

typedef void(^Error)(NSError *error);//请求失败

 

typedef NS_ENUM(NSInteger, RequestType) {

    RequestTypePOST,

    RequestTypeGET

};

 

 

@interface ZPRequestManager : NSObject

 

//属性保存外界传过来的Block

@property (nonatomic, copy) Finish finish;

@property (nonatomic, copy) Error error;

 

 

//网络请求类

 

//给这个类一个网址、参数、请求方式 让这个类返回数据(NSData)

//1、属性  2、方法(给这个类东西)

//1、Block  2、代理  3、方法返回值(暂不适用)(让这个类返回东西)

 

+ (void)requestWithUrl:(NSString *)urlSting requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error;

 

 

@end

 

 

#import "ZPRequestManager.h"

 

@implementation ZPRequestManager

 

 

+ (void)requestWithUrl:(NSString *)urlSting requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error{

    ZPRequestManager *request = [[ZPRequestManager alloc] init];

    [request requestWithUrl:urlSting requestType:requestType parDic:parDic finish:finish error:error];

}

 

- (void)requestWithUrl:(NSString *)urlSting requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error{

    

    self.finish = finish;

    self.error = error;

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlSting]];

    if (requestType == RequestTypePOST) {

        [request setHTTPMethod:@"POST"];

        if (parDic.count != 0) {

            [request setHTTPBody:[self dicToDataWithDic:parDic]];

        }

    }

    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        if (error) {

            self.error(error);

        } else {

            dispatch_async(dispatch_get_main_queue(), ^{

                self.finish(data);

            });

        }

    }];

    [task resume];

    

}

 

- (NSData *)dicToDataWithDic:(NSDictionary *)dic{

    //把字典里的简直对按照 Key=Value 拼接成字符串,最后用&符号连接所有拼接好的字符串

    

    NSMutableArray *array = [NSMutableArray array];

    for (NSString *key in dic) {

        NSString *string = [NSString stringWithFormat:@"%@=%@", key, dic[key]];

        [array addObject:string];

    }

    NSString *dataString = [array componentsJoinedByString:@"&"];

    return [dataString dataUsingEncoding:NSUTF8StringEncoding];

}

 

 

@end

 

posted @ 2016-07-27 18:01  DreamOfChina  阅读(162)  评论(0编辑  收藏  举报