您的位置:首页 > 理论基础 > 计算机网络

多线程 网络

2016-03-21 19:59 501 查看

GCD的队列类型

并发队列

自己创建的

全局

串行队列

主队列

自己创建的

## 多线程

NSThread

GCD

队列

并发队列

全局队列

自己创建

串行队列

自己创建

主队列

任务:block

函数

sync:同步函数

async:异步函数

单例模式

NSOperation

RunLoop

同一时间只能选择一个模式运行

常用模式

Default:默认

Tracking:拖拽UIScrollView

NSOperationQueue的队列类型

主队列

[NSOperationQueue mainQueue]

凡是添加到主队列中的任务(NSOperation),都会放到主线程中执行

非主队列(其他队列)

[[NSOperationQueue alloc] init]

同时包含了:串行、并发功能

添加到这种队列中的任务(NSOperation),就会自动放到子线程中执行

HTTP请求的常见方法

GET

所有参数拼接在URL后面,并且参数之间用&隔开

比如http://520it.com?name=123&pwd=345

传递了2个参数给服务器

name参数:123

pwd参数:345

没有请求体

一般用来查询数据

POST

所有参数都放在
请求体


一般用来修改、增加、删除数据

创建HTTP请求

GET

// 请求路径
NSString *urlString = @"http://520it.com?name=张三&pwd=123";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

// 创建URL
NSURL *url = [NSURL URLWithString:urlString];

// 创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

// 设置请求方法(默认就是GET请求)
request.HTTPMethod = @"GET";


POST

// 请求路径
NSString *urlString = @"http://520it.com/图片";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

// 创建URL
NSURL *url = [NSURL URLWithString:urlString];

// 创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

// 设置请求方法
request.HTTPMethod = @"POST";

// 设置请求体
request.HTTPBody = [@"name=张三&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];


使用NSURLConnection发送HTTP请求

发送同步请求

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;
// 这个方法是阻塞式的,会在当前线程发送请求
// 当服务器的数据完全返回时,这个方法才会返回,代码才会继续往下执行


发送异步请求-block

+ (void)sendAsynchronousRequest:(NSURLRequest*) request
queue:(NSOperationQueue*) queue
completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler;
// 会自动开启一个子线程去发送请求
// 当请求完毕(成功\失败),会自动调用handler这个block
// handler这个block会放到queue这个队列中执行


发送异步请求-delegate

创建NSURLConnection对象

// startImmediately==YES,创建完毕后,自动发送异步请求
- (instancetype)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;
- (instancetype)initWithRequest:(NSURLRequest *)request delegate:(id)delegate; // 创建完毕后,自动发送异步请求
+ (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate; // 创建完毕后,自动发送异步请求


发送请求

[connection start];


遵守
NSURLConnectionDataDelegate
协议,实现协议中的代理方法

// 当接收到服务器的响应时就会调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

// 每当接收到服务器返回的数据时就会调用1次(数据量大的时候,这个方法就会被调用多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

// 当服务器的数据完全返回时调用(服务器的数据接收完毕)
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

// 当请求失败的时候调用
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;


取消请求

[connection cancel];


NSString和NSData的互相转换

NSString -> NSData

NSData *data = [@"520it.com" dataUsingEncoding:NSUTF8StringEncoding];


NSData -> NSString

NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];


//发送请求给服务器,加载右侧的数据
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"a"] = @"list";
params[@"c"] = @"subscribe";
params[@"category_id"] =@(c.id);
[[AFHTTPSessionManager manager] GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
//字典转模型数组
NSArray *users = [XJQRecommendUser objectArrayWithKeyValuesArray:responseObject[@"list"]];

//添加当前类别对应的用户组
[c.users addObjectsFromArray:users];
//刷新表格
[self.detailVC reloadData];

} failure:^(NSURLSessionDataTask *task, NSError *error) {
[SVProgressHUD showErrorWithStatus:@"加载数据失败"];
}];


网络

HTTP请求

GET请求

// URL
NSString *urlStr = @"http://xxxxx.com";
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString:urlStr];

// 请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];


POST请求

// URL
NSString *urlStr = @"http://xxxxx.com";
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString:urlStr];

// 请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"username=123&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];


数据解析

JSON

NSJSONSerialization

XML

SAX: NSXMLParser

DOM: GDataXML

NSURLConnection(iOS9已经过期)

同步方法

异步方法-block

异步方法-代理

NSURLSession

发送一般的GET\POST请求

NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

}];

[task resume];


下载文件 - 不需要离线断点

NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {

}];

[task resume];


下载文件 - 需要离线断点

开启任务

// 创建session
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];

// 设置请求头(告诉服务器第1024个字节开始下载)
[request setValue:@"bytes=1024-" forHTTPHeaderField:@"Range"];

// 创建任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:request];

// 开始任务
[task resume];


实现代理方法

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
// 打开NSOutputStream

// 获得文件的总长度

// 存储文件的总长度

// 回调
completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
// 利用NSOutputStream写入数据

// 计算下载进度
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
// 关闭并且清空NSOutputStream

// 清空任务task
}


文件上传

设置请求头

拼接请求体

文件参数

其他参数(非文件参数)

NSURLSessionUploadTask

NSURLSessionUploadTask *task = [[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

}];

[task resume];


AFN

GET

// AFHTTPSessionManager内部包装了NSURLSession
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];

NSDictionary *params = @{
@"username" : @"520it",
@"pwd" : @"520it"
};

[mgr GET:@"http://120.25.226.186:32812/login" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"请求成功---%@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"请求失败---%@", error);
}];


POST

// AFHTTPSessionManager内部包装了NSURLSession
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];

NSDictionary *params = @{
@"username" : @"520it",
@"pwd" : @"520it"
};

[mgr POST:@"http://120.25.226.186:32812/login" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"请求成功---%@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"请求失败---%@", error);
}];


文件上传

AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];

[mgr POST:@"http://120.25.226.186:32812/upload" parameters:@{@"username" : @"123"}
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// 在这个block中设置需要上传的文件
//            NSData *data = [NSData dataWithContentsOfFile:@"/Users/xiaomage/Desktop/placeholder.png"];
//            [formData appendPartWithFileData:data name:@"file" fileName:@"test.png" mimeType:@"image/png"];

//            [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/xiaomage/Desktop/placeholder.png"] name:@"file" fileName:@"xxx.png" mimeType:@"image/png" error:nil];

[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/xiaomage/Desktop/placeholder.png"] name:@"file" error:nil];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"-------%@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {

}];


UIWebView

加载请求

JS和OC的互相调用

利用NSInvocation实现performSelector无限参数

异常捕捉

NSException

崩溃统计(第三方)

友盟

Flurry

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