NSURLSession的网络请求类

ios9以后弃用NSURLConnection的方法,用NSURLSession封装网络请求:

根据返回类型建三个方法去请求

改进demohttps://blog.csdn.net/gwh111/article/details/79700933

//对于json的请求
+ (void)postSessionWithJsonUrlStr:(NSString *)urlStr ParamterStr:(NSString *)paramsString FinishCallbackBlock:(void (^)(NSDictionary *, NSString *))block;

//对于html的请求
+ (void)postSessionWithHtmlUrlStr:(NSString *)urlStr ParamterStr:(NSString *)paramsString FinishCallbackBlock:(void (^)(NSString *, NSString *))block;

//对于无需应答的请求不需要回调
+ (void)postSessionWithNoReplyUrlStr:(NSString *)urlStr ParamterStr:(NSString *)paramsString;

前两个需要回调,需要在h文件声明回调类型

void (^finishCallbackBlock)(NSDictionary *resultDic,NSString *errorString); // 执行完成后回调的block
void (^finishHtmlCallbackBlock)(NSString *resultHtmlString,NSString *errorString);

在m文件完成方法:

+ (void)postSessionWithJsonUrlStr:(NSString *)urlStr ParamterStr:(NSString *)paramsString FinishCallbackBlock:(void (^)(NSDictionary *,NSString *))block{
    
    GHttpSessionTask *executorDelegate = [[GHttpSessionTask alloc] init];
    executorDelegate.finishCallbackBlock = block; // 绑定执行完成时的block
    
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession  *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:executorDelegate delegateQueue:nil];
    NSURLSessionDownloadTask *mytask=[session downloadTaskWithRequest:[self postRequestWithUrlString:urlStr andParamters:paramsString]];
    [mytask resume];
}

+ (void)postSessionWithHtmlUrlStr:(NSString *)urlStr ParamterStr:(NSString *)paramsString FinishCallbackBlock:(void (^)(NSString *, NSString *))block{
    
    GHttpSessionTask *executorDelegate = [[GHttpSessionTask alloc] init];
    executorDelegate.finishHtmlCallbackBlock = block; // 绑定执行完成时的block
    
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession  *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:executorDelegate delegateQueue:nil];
    NSURLSessionDownloadTask *mytask=[session downloadTaskWithRequest:[self postRequestWithUrlString:urlStr andParamters:paramsString]];
    [mytask resume];
}

+ (void)postSessionWithNoReplyUrlStr:(NSString *)urlStr ParamterStr:(NSString *)paramsString{
    
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession  *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];
    NSURLSessionDownloadTask *mytask=[session downloadTaskWithRequest:[self postRequestWithUrlString:urlStr andParamters:paramsString]];
    [mytask resume];
}

//创建request
+ (NSURLRequest *)postRequestWithUrlString:(NSString *)urlString andParamters:(NSString *)paramsString{

    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];
    request.HTTPBody = [paramsString dataUsingEncoding:NSUTF8StringEncoding];

    [request setTimeoutInterval:10];
    
    //设置请求头
    [request setValue:[NSString stringWithFormat:@"%@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]] forHTTPHeaderField:@"appVersion"];
    //[request setAllHTTPHeaderFields:nil];
    NSLog(@"header=%@",[request allHTTPHeaderFields]);
    return request;
}

代理方法

#pragma mark NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
    
    //判断回调的数据是否为空
    //判断回调的数据格式是否正确
    //判断签名是否正确
    if (finishCallbackBlock) {
        NSData *data=[NSData dataWithContentsOfURL:location];
        NSString *resultString= [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"finish callback block, result json string: %@", resultString);
        NSDictionary *JSON =
        [NSJSONSerialization JSONObjectWithData: data
                                        options: NSJSONReadingMutableLeaves
                                          error: nil];
        if (JSON) {
            finishCallbackBlock(JSON,nil);
        }else{
            finishCallbackBlock(nil,@"服务器未响应");
        }
    }else if(finishHtmlCallbackBlock){
        NSData *data=[NSData dataWithContentsOfURL:location];
        NSString *resultString= [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        if (resultString) {
            finishHtmlCallbackBlock(resultString,nil);
        }
    }
    
    
}

/* Sent periodically to notify the delegate of download progress. */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    //刷新进度条的delegate方法,同样的,获取数据,调用主线程刷新UI
    double currentProgress = totalBytesWritten/totalBytesExpectedToWrite;
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"currentProgress=%f",currentProgress);
    });
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
    
}

//防止重复回调 只在错误时回调
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error{
    if (finishCallbackBlock) { // 如果设置了回调的block,直接调用
        if (error) {
            NSString *errorString=[error description];
            NSLog(@"network error=%@ code=%ld",errorString,error.code);
            if (error.code==-1001) {
                errorString=@"请求超时";
            }
            finishCallbackBlock(nil,errorString);
        }
    }else if(finishHtmlCallbackBlock){
        if (error) {
            NSString *errorString=[error description];
            NSLog(@"network error=%@ code=%ld",errorString,error.code);
            if (error.code==-1001) {
                errorString=@"请求超时";
            }
            finishHtmlCallbackBlock(nil,errorString);
        }
    }
}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值