数据的网络请求有两类: 同步请求和异步请求
又可以归结为三种: 第一种:同步请求, 第二种:异步 Get 协议请求和异步 Get block 请求, 第三种: Post block 请求
从 iOS9.0之后, 默认是 https 请求, 如果想继续使用 http 请求, 需要在info.plist 点右键加一句话
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
在进行网络请求操作之前要在工程的 info.plist 文件中粘贴上
1. 同步请求
首先在ViewController中创建UIImageView
#import "ViewController.h"
@interface ViewController ()
- (IBAction)syn:(id)sender;
定义两个属性
@property(nonatomic, retain) UIImageView *imageView;
//用来装每次请求的数据
@property(nonatomic, retain) NSMutableData *data;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 从 iOS9.0之后, 默认是 https 请求, 如果想继续使用 http 请求, 需要在info.plist 点右键加一句话
// <key>NSAppTransportSecurity</key>
// <dict>
// <key>NSAllowsArbitraryLoads</key>
// <true/>
// </dict>
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(140, 60, 100, 100)];
[self.view addSubview: self.imageView];
self.imageView.backgroundColor = [UIColor grayColor];
[_imageView release];
}
- (IBAction)syn:(id)sender {
获取网址的字符串
NSString *urlStr = @"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg";
//把网址的字符串变成 NSURL
NSURL *url = [NSURL URLWithString:urlStr];
//把 url 对应的内容变成 NAData
NSData *data = [NSData dataWithContentsOfURL:url];
self.imageView.image = [UIImage imageWithData:data];
}
2. 异步 Get block 请求
@interface ViewController ()<NSURLSessionDelegate>
- (IBAction)syn:(id)sender;
- (IBAction)asyProtocolGet:(id)sender;
- (IBAction)asynBlockGet:(id)sender;
- (IBAction)asynBlockPost:(id)sender;
@property(nonatomic, retain) UIImageView *imageView;
//用来装每次请求的数据
@property(nonatomic, retain) NSMutableData *data;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (IBAction)asyProtocolGet:(id)sender {
NSString *strURL = @"http://api.map.baidu.com/place/v2/search?query=银行®ion=大连&output=json&ak=6E823f587c95f0148c19993539b99295";
//一个 url 有字母(大小写),数字和特殊符号/, &, $, ?, = 组成, 一般来说没有汉字, 所以当请求包里有种有汉字的时候, 需要手动给 url 转码,
strURL = [strURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:strURL]];
NSLog(@"%@", strURL);
//需要把 strURL 转换成 NSURL
NSURL *url = [NSURL URLWithString:strURL];
NSData *data = [NSData dataWithContentsOfURL:url];
self.imageView.image = [UIImage imageWithData:data];
//创建一个请求对象
NSMutableURLRequest *repuest = [NSMutableURLRequest requestWithURL:url];
//创建NSURLSecssion对象
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//创建一个任务对象
NSURLSessionTask *task = [session dataTaskWithRequest:repuest];
//执行任务, 如果不写, 整个任务不会自动执行
[task resume];
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
NSLog(@"%@", response);
//这个方法回吧服务器相应的信息返回给我们, 也就是说 response, 在这里能查到 http 状态码, status code, 200是请求成功, 404没找到指定页面, 500服务器出问题, 所以 response 可以知道请求的相应信息, 便于查找.
//当服务器相应之后, 需要允许服务器相应, 才能继续接受信任方法就是调用第四个参数 block 让他完成这个功能
completionHandler(NSURLSessionResponseAllow);
//允许完之后, 初始化接收数据的容器, data.
self.data = [NSMutableData data];
}
#pragma mark - 这个方法会持续的从服务器接收返回的数据, 会被多次调用, 在这个方法里可以用 self.data 对数据进行累加, 等到最后一个数据完成之后, 就完成了整个请求过程
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data {
//累加
[self.data appendData:data];
}
#pragma mark - 这个协议方法一般会在完成请求过请求失败的时候出现, 区分的话就是参数 error, 如果失败, error 就会有值, 反之为空.
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error {
if (error == nil) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.data options:0 error:nil];
NSLog(@"%@", dic);
} else {
NSLog(@"请求失败");
}
}
3. 异步 Get block 请求
#import "ViewController.h"
@interface ViewController ()
- (IBAction)asynBlockGet:(id)sender;
@property(nonatomic, retain) UIImageView *imageView;
//用来装每次请求的数据
@property(nonatomic, retain) NSMutableData *data;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)asynBlockGet:(id)sender {
NSString *strURL = @"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/activitylist.php";
NSURL *URL = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
//创建一个 session 对象
NSURLSession *session = [NSURLSession sharedSession];
//创建一个任务对象
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//json 解析
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", dic);
NSLog(@"%@", response);
}];
//执行一下任务
[task resume];
}
4.异步 Post block 请求
#import "ViewController.h"
@interface ViewController ()
- (IBAction)asynBlockGet:(id)sender;
@property(nonatomic, retain) UIImageView *imageView;
//用来装每次请求的数据
@property(nonatomic, retain) NSMutableData *data;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)asynBlockPost:(id)sender {
NSString *str = @"http://api2.pianke.me/pub/today";
NSURL *url = [NSURL URLWithString:str];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//设置请求方法, 默认是 GET
[request setHTTPMethod:@"POST"];
NSString *bodyStr = @"start=%ld&client=2&limit=10";
//需要把附件字符转换成 NSData
NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:bodyData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", dic);
}];
[task resume];
}
总结:异步的 Get block 请求用的比较多, 代码数量不多记忆也方便, 但是使用时要注意数据的刷新