博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
NSURLSession 简介
阅读量:5152 次
发布时间:2019-06-13

本文共 5694 字,大约阅读时间需要 18 分钟。

步骤:

(1) 得到 session 对象, NSURLSession *session = [NSURLSession sharedSession];
(2) 创建一个task, 任何一个请求都是一个任务

NSURLSessionDataTask // 普通任务NSURLSessionDownLoadTask // 文件下载任务NSURLSessionUploadTask // 文件上传任务

NSURLSession 实现 GET 请求

- (IBAction)login {    //判断账号与密码是否为空    NSString *name = _accountText.text;    if (name == nil || name.length == 0){        NSLog(@"请输入账号");        return;    }    NSString *pwd = _pwdText.text;    if (pwd == nil || pwd.length == 0){        NSLog(@"请输入密码");        return;    }    //创建URL    NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/Server/login?username=%@&pwd=%@", name, pwd];    //用NSURLSession实现登录    [self sessionWithUrl:urlStr];}- (void)sessionWithUrl:(NSString *)urlStr{    NSURL *url = [NSURL URLWithString:urlStr];    //用NSURLConnection实现登录     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    request.HTTPMethod = @"GET";    NSURLSession *session = [NSURLSession sharedSession];    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {        if (data == nil || error != nil) {            NSLog(@"请求失败");            return;        }        //JSON解析        NSError *error2;        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error2];        if (error2) {            NSLog(@"解析失败 -- %@", error2);        }        NSLog(@"数据为 -- %@", dict);    }];    [task resume];}

NSURLSession 实现 POST 请求:

- (IBAction)login {    //判断账号与密码是否为空    NSString *name = _accountText.text;    if (name == nil || name.length == 0){        NSLog(@"请输入账号");        return;    }    NSString *pwd = _pwdText.text;    if (pwd == nil || pwd.length == 0){        NSLog(@"请输入密码");        return;    }    //用NSURLSession实现登录    //创建URL    NSString *urlStr = @"http://localhost:8080/Server/login";    [self sessionWithUrl:urlStr];}- (void)sessionWithUrl:(NSString *)urlStr{    NSURL *url = [NSURL URLWithString:urlStr];    //用NSURLConnection实现登录     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    //POST请求    request.HTTPMethod = @"POST";    NSString *prama = [NSString stringWithFormat:@"username=%@&pwd=%@", _accountText.text, _pwdText.text];    //中文转码    [prama stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    //转码    request.HTTPBody = [prama dataUsingEncoding:NSUTF8StringEncoding];    NSURLSession *session = [NSURLSession sharedSession];    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {        if (data == nil || error != nil) {            NSLog(@"请求失败");            return;        }        //JSON解析        NSError *error2;        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error2];        if (error2) {            NSLog(@"解析失败 -- %@", error2);        }        NSLog(@"数据为 -- %@", dict);    }];    [task resume];}

NSURLSession 实现 断点续传:

//断点下载@property (nonatomic, strong) NSURLSession *session;@property (nonatomic, strong) NSURLSessionDownloadTask *task;@property (nonatomic, strong) NSData *resumeData;@property (weak, nonatomic) IBOutlet UIProgressView *progressView;//懒加载- (NSURLSession *)session{    if (!_session) {        NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];        _session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];    }    return _session;}/** *  NSURLSession实现断点下载 */- (IBAction)startDowbLoad:(id)sender {    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/videos/minion_01.mp4"];    self.task = [self.session downloadTaskWithURL:url];    //开始下载    [self.task resume];}/** *  暂停下载 */- (IBAction)pauseDownLoad:(id)sender{    __weak typeof (self) vc = self;    /**     *  @param resumeData 包含了继续下载开始的位置和下载的URL     */    [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {        vc.resumeData = resumeData;        self.task = nil;    }];}/** *  恢复下载 */- (IBAction)resumeDownLoad:(id)sender {    //传入上次下载的数据    self.task = [self.session downloadTaskWithResumeData:self.resumeData];    //开始下载    [self.task resume];    //清空    self.resumeData = nil;}#pragma mark - NSURLSessionDelegate 代理方法//下载完成调用- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{    //下载完成后,写入 caches 文件中    NSString *cachesFile = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];    NSFileManager *mgr = [NSFileManager defaultManager];    [mgr moveItemAtPath:location.path toPath:cachesFile error:nil];}/** *  下载过程中调用这个方法, 每当下载完(写完)一部分时会调用, (可能被调用多次) * *  @param bytesWritten              这次写了多少 *  @param totalBytesWritten         累计写了多少 *  @param totalBytesExpectedToWrite 文件的总长度 */- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{    self.progressView.progress = (double)totalBytesWritten / totalBytesExpectedToWrite;}//恢复下载的时候调用- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{}

转载于:https://www.cnblogs.com/xiaocai-ios/p/7779769.html

你可能感兴趣的文章
vb6.0 快捷键
查看>>
201671010127 2016-2017-12 初学图形用户界面
查看>>
POJ-1061 青蛙的约会
查看>>
ZOJ-2836 Number Puzzle
查看>>
poj3463 Sightseeing(读题很重要)
查看>>
hdu6181 How Many Paths Are There(次短路条数[模板])
查看>>
python学习日记(常用模块)
查看>>
正则表达式和样式匹配
查看>>
8_分析一下JVM
查看>>
进程PCB
查看>>
用js来实现那些数据结构09(集合01-集合的实现)
查看>>
Sqlserver 2008 R2安装的盘符空间不够用的解决办法
查看>>
White Stripes UI 素材
查看>>
Java通过反射机制修改类中的私有属性的值
查看>>
1038 Recover the Smallest Number (30 分)
查看>>
网站系统开发需要掌握的技术
查看>>
Android提供两个常用的消息弹出框【Toast和Alert】
查看>>
使用SQL Server发送邮件时遇到的诡异事件
查看>>
tomcat下jsp要加工程名后缀才能访问的问题解决
查看>>
confluence安装
查看>>