NSURLSession
- 使用步骤
- 创建NSURLSession
- 创建Task
- 执行Task
NSURLSessionDataTask
NSURL *url = [NSURL URLWithString:@"http://124.25.226.186:32812/login?username=baoduit&pwd=baiduit"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
[task resume];
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=baoduit&pwd=baoduit"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
[task resume];
NSURL *url = [NSURL URLWithString:@"http://123.25.226.186:32812/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
[task resume];
- NSURLSessionDataDelegate代理注意事项
// 1.获得NSURLSession对象
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
+ NSURLSessionDataDelegate`默认不会接受数据`
/**
* 1.接收到服务器的响应
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
NSLog(@"%s", __func__);
NSLog(@"%@", [NSThread currentThread]);
completionHandler(NSURLSessionResponseAllow);
}
/**
* 2.接收到服务器的数据(可能会被调用多次)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
NSLog(@"%s", __func__);
}
/**
* 3.请求成功或者失败(如果失败,error有值)
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"%s", __func__);
}
NSURLSessionDownloadTask
NSURL *url = [NSURL URLWithString:@"http://123.25.226.186:32812/resources/videos/minion_01.mp4"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
NSLog(@"%@", location.absoluteString);
NSFileManager *manager = [NSFileManager defaultManager];
NSString *toPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
toPath = [toPath stringByAppendingPathComponent:response.suggestedFilename];
[manager moveItemAtURL:location toURL:[NSURL fileURLWithPath:toPath] error:nil];
}];
[task resume];
- DownloadTask断点下载
- 暂停: suspend
- 继续: resume
- 取消: cancel
- 区别并返回下载信息
[self.task cancelByProducingResumeData:^(NSData *resumeData) {
self.resumeData = resumeData;
}];
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
[self.task resume];
/**
* 每当写入数据到临时文件时,就会调用一次这个方法
* totalBytesExpectedToWrite:总大小
* totalBytesWritten: 已经写入的大小
* bytesWritten: 这次写入多少
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
NSLog(@"正在下载: %.2f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
NSLog(@"didResumeAtOffset fileOffset = %lld , expectedTotalBytes = %lld", fileOffset, expectedTotalBytes);
}
/**
* 下载完毕就会调用一次这个方法
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
NSLog(@"下载完毕");
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}
/**
* 任务完成
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"didCompleteWithError");
}
离线断点下载
NSMutableURLRequest *reuqest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
NSInteger currentBytes = KCurrentBytes;
NSString *range = [NSString stringWithFormat:@"bytes=%zd-", currentBytes];
[reuqest setValue:range forHTTPHeaderField:@"Range"];
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data;
NSURLSessionUploadTask
- 设置设置请求头, 告诉服务器是文件上传
- multipart/form-data; boundary=lnj
- 必须自己
严格按照格式
拼接请求体 - 请求体不能设置给request, 只能设置给fromData
- The body stream and body data in this request object are ignored.
+
[[self.session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}] resume];
[self.session uploadTaskWithRequest:<#(nonnull NSURLRequest *)#> fromFile:<#(nonnull NSURL *)#>]