NSURLSession

Posted 谢小锋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NSURLSession相关的知识,希望对你有一定的参考价值。

-(void)get{
    NSURLSession * session=[NSURLSession sharedSession];
    NSURLSessionTask * task=[session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.xiufa.com/BJUI/plugins/kindeditor_4.1.10/attached/image/20160427/20160427020327_69298.png"]] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        _imageview.image= [ UIImage imageWithData:data];
        NSLog(@"%@",[NSThread currentThread]);
    }];
    [task resume];
    
}
-(void)get2{
    NSURLSession * session=[NSURLSession sharedSession];
    NSURLSessionTask * task=[session dataTaskWithURL:[NSURL URLWithString:@"http://www.xiufa.com/BJUI/plugins/kindeditor_4.1.10/attached/image/20160427/20160427020327_69298.png"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        _imageview.image= [ UIImage imageWithData:data];
        NSLog(@"%@",[NSThread currentThread]);
    }];
    [task resume];
}//post 请求
-(void)post{
    NSURLSession * session=[NSURLSession sharedSession];
    NSMutableURLRequest * request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.xiufa.com/BJUI/plugins/kindeditor_4.1.10/attached/image/20160427/20160427020327_69298.png"]];
    [email protected]"GET";
    request.HTTPBody=[@"" dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionTask * task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSOperationQueue * que=[NSOperationQueue mainQueue];
        [que addOperationWithBlock:^{
            _imageview.image= [ UIImage imageWithData:data];
            NSLog(@"%@",[NSThread currentThread]);
            
        }];
    }];
    [task resume];
    
}
-(void)download{
    NSURLSession * session=[NSURLSession sharedSession];
    
    NSURLSessionDownloadTask * down= [session downloadTaskWithURL:[NSURL URLWithString:@"http://www.xiufa.com/BJUI/plugins/kindeditor_4.1.10/attached/image/20160427/20160427020327_69298.png"] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString * file=[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        NSFileManager * mag=[NSFileManager defaultManager];
        [mag moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
        //        [mag moveItemAtPath:location toURL:[NSURL fileURLWithPath:file] error:nil];
        NSLog(@"%@",location);
        
    }];
    [down resume];
}

 

 

 

-(void)down{
    NSURLSession * session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
    NSURLSessionDataTask * task=[session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.bz55.com/uploads/allimg/140918/138-14091PZ001.jpg"]]];
    [task resume];

}
//2接收服务器的数据
-(void)URLSession:(NSURLSession *)session dataTask:(nonnull NSURLSessionDataTask *)dataTask didReceiveData:(nonnull NSData *)data{
    NSLog(@"%s",__func__);

        [_data appendData:data];
        NSOperationQueue * quer=[NSOperationQueue mainQueue];
        
        [quer addOperationWithBlock:^{
            _imageview.image=[UIImage imageWithData:_data];
            
            NSLog(@"%@",[NSThread currentThread]);
        }];

    NSLog(@"%@",data);
}
//1接收服务器响应
-(void)URLSession:(NSURLSession *)session dataTask:(nonnull NSURLSessionDataTask *)dataTask didReceiveResponse:(nonnull NSURLResponse *)response completionHandler:(nonnull void (^)(NSURLSessionResponseDisposition))completionHandler{
    completionHandler(NSURLSessionResponseAllow);
    NSLog(@"%s",__func__);
}
//3请求失败或者成功
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    NSLog(@"%s",__func__);

    NSLog(@"%@",error);
}


大文件下载

-(void)downBig
{
    
    NSURLSession * session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
    
    NSURLSessionDownloadTask * down=[session downloadTaskWithURL: [NSURL URLWithString:@"http://www.xiufa.com/BJUI/plugins/kindeditor_4.1.10/attached/image/20160427/20160427020327_69298.png"]];
    [down resume];

}

 

 

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

/**
 *  每次写入数据到临时文件时,就会调用一次这个方法
 *  @param bytesWritten              这个词写入多少
 *  @param totalBytesWritten         已写入多少
 *  @param totalBytesExpectedToWrite 总大小
 */
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    NSLog(@"---%f---",1.0*totalBytesExpectedToWrite/totalBytesWritten);
}
//下载完毕
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    //文件将存放的真实路径
    NSString * file=[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    NSFileManager * mag=[NSFileManager defaultManager];
    [mag moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}

小文件下载

-(void)download{
    NSURLSession * session=[NSURLSession sharedSession];
    
    NSURLSessionDownloadTask * down= [session downloadTaskWithURL:[NSURL URLWithString:@"http://www.xiufa.com/BJUI/plugins/kindeditor_4.1.10/attached/image/20160427/20160427020327_69298.png"] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString * file=[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        NSFileManager * mag=[NSFileManager defaultManager];
        [mag moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
        //        [mag moveItemAtPath:location toURL:[NSURL fileURLWithPath:file] error:nil];
        NSLog(@"%@",location);
        
    }];
    [down resume];
}

 

 

 

//2接收服务器的数据
-(void)URLSession:(NSURLSession *)session dataTask:(nonnull NSURLSessionDataTask *)dataTask didReceiveData:(nonnull NSData *)data{
    NSLog(@"%s",__func__);

        [_data appendData:data];
        NSOperationQueue * quer=[NSOperationQueue mainQueue];
        
        [quer addOperationWithBlock:^{
            _imageview.image=[UIImage imageWithData:_data];
            
            NSLog(@"%@",[NSThread currentThread]);
        }];

    NSLog(@"%@",data);
}
//1接收服务器响应
-(void)URLSession:(NSURLSession *)session dataTask:(nonnull NSURLSessionDataTask *)dataTask didReceiveResponse:(nonnull NSURLResponse *)response completionHandler:(nonnull void (^)(NSURLSessionResponseDisposition))completionHandler{
    completionHandler(NSURLSessionResponseAllow);
    NSLog(@"%s",__func__);
}
//3请求失败或者成功
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    NSLog(@"%s",__func__);

    NSLog(@"%@",error);
}

 

以上是关于NSURLSession的主要内容,如果未能解决你的问题,请参考以下文章