NSURLSession实现Http传输的简单实现

.h文件

#import 

typedef void (^RequestSuccess) (NSData *data);
typedef void (^RequestFailure) (NSError *error);

@protocol JLHttpRequestDelegate 

- (void)RequestCompletion:(NSData *)data urlresponse:(NSURLResponse *)response error:(NSError *)error;

@end

@interface JLHTTPRequest : NSObject

@property (nonatomic,weak)id delegate;

- (void)RequestWithUrl:(NSString *)strurl;

// block
- (void)RequestWithUrl:(NSString *)strurl Success:(RequestSuccess) success Failure:(RequestFailure) failure;

@end

.m文件

#import "JLHTTPRequest.h"

@implementation JLHTTPRequest


- (void)RequestWithUrl:(NSString *)strurl
{
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:strurl]];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (self.delegate) {
            [self.delegate RequestCompletion:data urlresponse:response error:error];
        }
    }];
    
    [task resume];
}

// block
- (void)RequestWithUrl:(NSString *)strurl Success:(RequestSuccess)success Failure:(RequestFailure)failure
{
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:strurl]];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (success) {
            success(data);
        }
        if (failure) {
            failure(error);
        }
        
    }];
    
    [task resume];

}

@end


基于代理协议和block的封装


你可能感兴趣的:(iOS开发)