免费开源的iOS开发学习平台

iOS开发之网络编程:11-NSURLSession的简单使用

这篇文章我们用实例来讲解一下NSURLSession的基本用法。

1、NSURLSession实现POST请求

  • 设置请求(在聚合数据上申请【微信精选】数据)
    NSURL *url = [NSURL URLWithString:@"http://v.juhe.cn/weixin/query?"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [@"key=你申请的APPKEY" dataUsingEncoding:NSUTF8StringEncoding];
  • 创建NSURLSession,设置代理(遵守NSURLSessionDelegate协议),配置为默认配置,代理方法执行在主线程。
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
  • 创建任务
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
    {
        //请求成功,解析数据
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
                                                                           options:NSJSONReadingMutableContainers  error:nil];
        //获取所需数据
        NSDictionary *dict = dictionary[@"result"];
        NSArray *arr = dict[@"list"];
        NSDictionary *dic = arr[0];
        NSLog(@"%@",dic[@"title"]);
 }];
  • 启动任务(所有类型的task都要调用resume方法才会开始进行请求)
    [task resume];
  • NSURLSessionDelegate代理方法

session关闭回调

- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error;

与身份验证和证书安全问题相关的方法

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge  completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler;

后台任务完成后调用的方法

- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session NS_AVAILABLE_IOS(7_0);

2、下载文件

    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:@"http://qiniu.99ios.com/99ios/1479730067100.png"] ;
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        // location是沙盒中tmp文件夹下的一个临时url,文件下载后会存到这个位置,由于tmp中的文件随时可能被删除,所以我们需要自己需要把下载的文件挪到需要的地方
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        //打印文件被存储的路径
        NSLog(@"%@",path);
        // 剪切文件
        [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:path] error:nil];
    }];
    // 启动任务
    [task resume];