NSURLSessionDataTask是iOS7以后才会有的,取代NSURLConnection
参考:http://blog.csdn.net/ttf1993/article/details/46491113
1.基本使用
//GET请求(默认)
//创建session对象
NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/TFServer/video"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//创建一个任务
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSLog(@"----%d", data.length);
}];
//开始任务
[task resume];
NSURLSessionDataTask *dataTask = nil;//创建任务,先置空
if (imageURL.absoluteString.length) {
NSURLRequest *request = [NSURLRequest requestWithURL:imageURL];
if (request == nil) {
dispatch_async(dispatch_get_main_queue(), ^{
if (completion) {
completion(nil);
}
});
}
else {
//1 创建对象
NSURLSession *sesh = [NSURLSession sharedSession];
#if 0 //POST请求(默认为GET请求)
//设置request
request.HTTPMethod = @"post";
request.HTTPBody = [@"username=123&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];
#endif
// 创建任务
dataTask = [sesh dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//下载图片
NSError *error;
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL options:NSDataReadingMappedAlways error:&error]];
dispatch_async(dispatch_get_main_queue(), ^{
if (completion) {
completion(image);
}
});
});
}];
//3 开始请求任务
[dataTask resume];
}
}
return dataTask;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17