您的位置:首页 > 其它

NSURLSession的介绍与基本用法

2015-10-30 22:48 302 查看
对比
NSURLConnection中的存在很多问题,例如:
NSURLConnection是IOS2.0推出的古老而又经典的网络解决方案。
复杂的网络请求需要使用代理进行实现。
代理方式默认在主线程工作。
只提供了start&cancel方法,不能暂停。
在使用多线程时需要使用运行循环。
-------------------------------------------
NSURLSession是IOS7中新的网络接口,,与NSURLConnection是并列的。
当程序在前台时,NSURLSession与NSURLConnection大部分可以互相替代。
NSURLSession支持后台网络操作,除非用户强行关闭。
NSURLSession提供的功能:
通过URL将数据下载到内存。
通过URL将数据下载的到文件系统。
将数据上传到指定URL。
在后台完成上述功能。
对于小型数据,例如用户登录、下载小图像、JSON&XML仍然使用NSURLConnection的异步或者同步方法即可。
另外,我们不用再考虑NSURLSession的线程问题,因为苹果已经为我们做好了。
新建工程,代码如下:
//
//  ViewController.m
//  NSURLSession的基本使用
//
//  Created by apple on 15/10/30.
//  Copyright (c) 2015年 LiuXun. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
/**
使用NSURLSession肯定是异步,在子线程做耗时操作
我们只需要创建一个Session,发起一个任务,让任务resume就OK了
*/

- (void)viewDidLoad {
[super viewDidLoad];
// 1. url
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/videos.json"];

// 3. 由Session发起任务——异步操作
[[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

// 反序列化
id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(@"%@", result);

// 在主线程更新UI
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"更新UI");
});
}] resume];

NSLog(@"XXXXXX");
}

-(void)test1
{
// 1. url
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/videos.json"];

// 2. 创建一个会话Session
// 苹果直接提供了一个全局的Session(单例)
NSURLSession *session = [NSURLSession sharedSession];

// 3. 由Session发起任务
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

// 反序列化
id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(@"%@", result);
}];

// 需要把任务开启。任务默认都是挂起的。
[task resume];

}
@end
运行结果如下:

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