URLSession

          NSURLSession是xcode7.0之后的请求网络的新API,是代替NSURLConnection的。在2013年苹果的技术发布会上首次提出,xcode7.0后正式废除NSURLConnection方法。

   不同于NSURLConnection需要设置同步异步请求,NSURLSession是自动创建子线程来进行网络请求,所以要在回调方法中需要用主线程刷新。

 而且NSURLSession支持后台网络操作。可以实现下载数据到内存,下载数据到文件系统,上传到服务器,断点续传,下载任务跟进以及在后台完成上述方法。

  

    NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"sad" withExtension:nil];
    NSURL *url = [NSURL URLWithString:@"12"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //请求模式设为PUT   文件大小无限制,可以覆盖文件
    request.HTTPMethod = @"PUT";
    NSString *authStr = @"admin:sadadssa";
    NSData *data = [authStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64Str = [data base64EncodedStringWithOptions:0];
    NSString *resultStr = [NSString stringWithFormat:@"Basic %@",base64Str];
    [request setValue:resultStr forKey:@"Authorization"];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    //设置本类为代理,创建子队列
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
    
    //设置监听任务
    NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromFile:fileURL];
    [task resume];

#pragma mark - 上传进度的代理方法  
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend  
{  
    // bytesSent totalBytesSent totalBytesExpectedToSend  
    // 发送字节(本次发送的字节数)    总发送字节数(已经上传的字节数)     总希望要发送的字节(文件大小)  
    NSLog(@"%lld-%lld-%lld-", bytesSent, totalBytesSent, totalBytesExpectedToSend);  
    // 已经上传的百分比  
    float progress = (float)totalBytesSent / totalBytesExpectedToSend;  
    NSLog(@"%f", progress);  
}  

#pragma mark - 上传完成的代理方法  
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error  
{  
    NSLog(@"完成 %@", [NSThread currentThread]);  
}  
@end  
  //请求数据
    NSString *URLStr = [NSString stringWithFormat:@"www.baidu.com"];
    NSURL *url = [NSURL URLWithString:URLStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setTimeoutInterval:20];//设置超时时间
    [request setCachePolicy:NSURLRequestReturnCacheDataElseLoad];//设置缓存策略
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"%@",dataStr);
            });
        }
    }];



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值