GCD的队列类型
- 并发队列
- 串行队列
- NSThread
- GCD
- NSOperation
- RunLoop
- 同一时间只能选择一个模式运行
- 常用模式
- Default:默认
- Tracking:拖拽UIScrollView
NSOperationQueue的队列类型
- 主队列
- [NSOperationQueue mainQueue]
- 凡是添加到主队列中的任务(NSOperation),都会放到主线程中执行
- 非主队列(其他队列)
- [[NSOperationQueue alloc] init]
- 同时包含了:串行、并发功能
- 添加到这种队列中的任务(NSOperation),就会自动放到子线程中执行
HTTP请求的常见方法
- GET
- 所有参数拼接在URL后面,并且参数之间用&隔开
- 没有请求体
- 一般用来查询数据
- POST
- 所有参数都放在
请求体
中 - 一般用来修改、增加、删除数据
创建HTTP请求
NSString *urlString = @"http://520it.com?name=张三&pwd=123";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"GET";
NSString *urlString = @"http://520it.com/图片";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
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;
发送异步请求-delegate
- (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;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
[connection cancel]
NSString和NSData的互相转换
NSData *data = [@"520it.com" dataUsingEncoding:NSUTF8StringEncoding];
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请求
NSString *urlStr = @"http://xxxxx.com";
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL: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
- XML
- SAX: NSXMLParser
- DOM: GDataXML
NSURLConnection(iOS9已经过期)
NSURLSession
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
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);
}];
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无限参数
- 异常捕捉