您的位置:首页 > 其它

NSURLSession的应用

2016-01-28 16:46 357 查看
iOS7以后发布了NSURLSession用来替换NSURLConnection,NSURLSession使用方式有以下两种:

1.block方式

(1)创建的步骤

获取单例会话对象

创建URL对象

隐含创建request

创建NSURLSessionDataTask

// 1.获取会话对象
NSURLSession *session = [NSURLSession sharedSession];
//另外一种生成默认的GET请求的方法
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/video"];

NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"%@", dict);


(2)使用NSURLSessionDataTask

创建session

创建URL

创建URLRequest

创建NSURLSessionDataTask

// 2.创建的一URL地址
NSURL *url = [NSURL URLWithString:@"http://192.168.15.172:8080/MJServer/login"];
// 3.创建一个请求对象
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"username=123&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];

NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"%@", dict);
}];

[task resume];


(3)使用NSURLSessionDownloadTask

// 1.得到session对象

NSURLSession *session = [NSURLSession sharedSession];

// 2.创建URL对象

NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/test.mp4"];

NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [caches stringByAppendingPathComponent:response.suggestedFilename];

NSFileManager *fileManager = [NSFileManager defaultManager];

[fileManager moveItemAtPath:location.path toPath:filePath error:nil];

}];


2.代理方式

(void)downLoadTask2 {

NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];

// 使用配置对象获取会话对象

NSURLSession *session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];

// 创建一个URL

NSURL *url = [NSURL URLWithString:@”http://localhost:8080/MJServer/resources/test.mp4“];

NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];

[task resume];

}

- (void)URLSession:(NSURLSession )session downloadTask:(NSURLSessionDownloadTask )downloadTask didFinishDownloadingToURL:(NSURL *)location {

NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

NSString *filePath = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];

NSFileManager *fileManager = [NSFileManager defaultManager];

[fileManager moveItemAtPath:location.path toPath:filePath error:nil];

}

(void)URLSession:(NSURLSession )session downloadTask:(NSURLSessionDownloadTask )downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {

double progress = (double)totalBytesWritten / totalBytesExpectedToWrite;

NSLog(@”已经下载了:%f”, progress);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: