1.NSURLsessionDataTask
1//确定URL2NSString *urlStr =@"http://localhost/试试看";3urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];4NSURL *url =[NSURL URLWithString:urlStr];56//确定request7NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0timeoutInterval:2.0f];89//确定会话10NSURLSession *session =[NSURLSession sharedSession];1112//由会话生成任务13NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {14NSLog(@"response-- %@",response);15NSLog(@"data--%@",data);1617//刷新UI,一定要返回主线程去刷新18dispatch_async(dispatch_get_main_queue(), ^{19[self.imageView setImage:[UIImage imageWithData:data]];20});2122}];23// URLSession默认生成的任务都是挂起状态,需要使用以下语句执行任务24[dataTask resume];
2.NSURLSessionDownloadTask实现简单的下载功能
1//确定URL2NSString *urlStr =@"http://localhost/试试看";3urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];4NSURL *url =[NSURL URLWithString:urlStr];56//确定request7NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0timeoutInterval:2.0f];89//确定会话10NSURLSession *session =[NSURLSession sharedSession];1112//由会话生成任务13NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {14//从tmp中拷贝文件到cache15NSString *cachePath =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];16NSURL *cachePathURL =[NSURL fileURLWithPath:cachePath];17NSString *fileNameBymd5=[[[response URL] absoluteString] MD5];18NSURL *fileURL =[cachePathURL URLByAppendingPathComponent: fileNameByMD5];1920NSFileManager *mgr =[NSFileManager defaultManager];21[mgr moveItemAtURL:location toURL:fileURL error:NULL];2223}];2425[downloadTask resume];
1- (NSString *)MD52{3constchar*cStr =[self UTF8String];4unsignedchardigest[CC_MD5_DIGEST_LENGTH];56CC_MD5(cStr, strlen(cStr), digest);78NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH *2];910for(inti =0; i < CC_MD5_DIGEST_LENGTH; i++) {11[result appendFormat:@"%02x", digest[i]];12}1314returnresult;15}
3.NSURLSessionDownloadTask实现复杂的下载功能:断点续传\后台下载
http://blog.csdn.net/majiakun1/article/details/38133789