NSURLSession的应用

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);

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值