1.NSURLSessionDataTask
// 確定URL NSString *urlStr = @"http://localhost/試試看"; urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:urlStr]; // 確定request NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0f]; // 確定會話 NSURLSession *session = [NSURLSession sharedSession]; // 由會話生成任務 NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSLog(@"response-- %@",response); NSLog(@"data--%@",data); // 刷新UI,一定要返回主線程去刷新 dispatch_async(dispatch_get_main_queue(), ^{ [self.imageView setImage:[UIImage imageWithData:data]]; }); }]; [dataTask resume];
2.NSURLSessionDownloadTask實現簡單的下載功能
// 確定URL NSString *urlStr = @"http://localhost/試試看"; urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:urlStr]; // 確定request NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0f]; // 確定會話 NSURLSession *session = [NSURLSession sharedSession]; // 由會話生成任務 NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) { // 從tmp中拷貝文件到cache NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSURL *cachePathURL = [NSURL fileURLWithPath:cachePath]; NSString *fileNameByMD5 = [[[response URL] absoluteString] MD5]; NSURL *fileURL = [cachePathURL URLByAppendingPathComponent: fileNameByMD5]; NSFileManager *mgr = [NSFileManager defaultManager]; [mgr moveItemAtURL:location toURL:fileURL error:NULL]; }]; [downloadTask resume];
- (NSString *)MD5 { const char *cStr = [self UTF8String]; unsigned char digest[CC_MD5_DIGEST_LENGTH]; CC_MD5(cStr, strlen(cStr), digest); NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2]; for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) { [result appendFormat:@"%02x", digest[i]]; } return result; }
3.NSURLSessionDownloadTask實現復雜的下載功能:斷點續傳\後台下載
http://blog.csdn.net/majiakun1/article/details/38133789