图片下载
NSString *api = @"http://i2.cqnews.net/car/attachement/jpg/site82/20120817/5404a6b61e3c1197fb211d.jpg";
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:api] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"response:%@",response);
UIImage *image = [UIImage imageWithData:data];
NSLog(@"error:%@",error);
}];
歌曲下载
{
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *task = [_session dataTaskWithRequest:mutiRequest];
[task resume];
}
//第一步: 接受响应
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
NSHTTPURLResponse *resp = (NSHTTPURLResponse*)response;
//文件总大小
NSLog(@"%lld",resp.expectedContentLength);
NSLog(@"--->%@",response);
if(resp.statusCode == 200){
completionHandler(NSURLSessionResponseAllow);
}
}
//第二步: 接受数据
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data{
NSLog(@"-->%ld",data.length);
[_datas appendData:data];
}
//第三步: 下载完成
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error{
if(!error){
NSLog(@"done");
}
else {
NSLog(@"error: %@", error);
}
}
网友评论