1 #import "ViewController.h" 2 #import "Header.h" 3 4 @interface ViewController () <NSURLConnectionDataDelegate> 5 6 @property (nonatomic, strong) NSMutableArray *dataArray; 7 8 @end 9 10 @implementation ViewController 11 12 // 懒加载 13 - (NSMutableArray *)dataArray { 14 15 if (!_dataArray) { 16 _dataArray = [NSMutableArray array]; 17 } 18 return _dataArray; 19 } 20 21 22 - (void)viewDidLoad { 23 [super viewDidLoad]; 24 // Do any additional setup after loading the view, typically from a nib. 25 } 26 27 #pragma mark - get异步请求 28 - (IBAction)getAsynchronousRequset:(UIButton *)sender { 29 30 // 1.创建url 31 NSURL *url = [NSURL URLWithString:GET_URL]; 32 33 34 // 2.创建请求 35 NSURLRequest *request = [NSURLRequest requestWithURL:url]; 36 37 38 // 3.链接服务器 39 // 方法一:Block方法实现 40 // 第一个参数:请求对象 41 // 第二个参数:线程队列 42 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { 43 // response是携带的接口信息 44 // data请求下来的数据,接下来会会使用到的 45 // connectionError错误信息 46 if (connectionError == nil) { 47 48 // 4.解析 49 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; 50 51 NSLog(@"%@", dic); 52 53 // 先开辟子线程解析数据,然后在主线程里刷新UI 54 } 55 56 }]; 57 58 } 59 60 61 #pragma mark - post异步请求 62 - (IBAction)postAsynchronousRequset:(UIButton *)sender { 63 64 // 1.创建url 65 NSURL *url = [NSURL URLWithString:POST_URL]; 66 67 68 // 2.创建请求 69 NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url]; 70 71 72 // 2.5.设置body 73 // 创建一个连接字符串(这个内容在以后的开发中接口文档都有标注) 74 NSString *dataStr = POST_BODY; 75 76 // 对连接字符串进行编码【这一步千万不能忘记】 77 NSData *postData = [dataStr dataUsingEncoding:NSUTF8StringEncoding]; 78 79 // 设置请求格式为post请求【在这里POST必须大写】 80 [mutableRequest setHTTPMethod:@"POST"]; 81 82 // 设置请求体(body) 83 [mutableRequest setHTTPBody:postData]; 84 85 86 // 3.链接服务器 87 // 方法一:Block方法 88 [NSURLConnection sendAsynchronousRequest:mutableRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { 89 90 if (connectionError == nil) { 91 // 4.解析 92 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; 93 NSLog(@"%@", dic); 94 } 95 }]; 96 97 }
时间: 2024-11-08 20:41:16