iOS-GET请求详细操作-GET设置请求头
2016-03-04 12:12
671 查看
难得一次备注相当详细的原生GET网络请求操作,强迫症一样记录下来和大家分享… 也备复制用
-(void)getResult{ _MB = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES]; //接口路径 NSString *path = @"http://a.apix.cn/apixlife/phone/phone"; //路径-+参数 NSString *pathWithPhoneNum = [NSString stringWithFormat:@"%@?phone=%@",path,_phoneNumFD.text]; //中文编码 NSString *urlPath = [pathWithPhoneNum stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; //URL NSURL *phoneURL = [NSURL URLWithString:urlPath]; //请求对象 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:phoneURL]; //请求方式 [request setHTTPMethod:@"GET"]; //请求头 [request setValue:@"92b5787ecd17417b718a2aaedc7e6ce8" forHTTPHeaderField:@"apix-key"]; //网络配置 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; //网络会话 NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration]; //任务 NSURLSessionDataTask *sessionTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { //回到主线程更新UI -> 撤销遮罩 dispatch_async(dispatch_get_main_queue(), ^{ [_MB hide:YES]; }); if (error) { NSLog(@"请求失败... %@",error); //提示用户请求失败! UIAlertController *AV = [UIAlertController alertControllerWithTitle:@"提示" message:@"抱歉,服务器错误,请稍后重试..." preferredStyle:UIAlertControllerStyleActionSheet]; [AV addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { //点击OK,进行相应操作,可置nil NSLog(@"您点击了OK.."); }]]; [self presentViewController:AV animated:YES completion:nil]; }else{ //JSON 解析 苹果原生效率最高 NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; if ([[result objectForKey:@"message"] isEqualToString:@"success"]) { //获取数据->主线程更新UI dispatch_async(dispatch_get_main_queue(), ^{ NSDictionary *data = [result objectForKey:@"data"]; NSString *city = [data objectForKey:@"city"]; NSString *province = [data objectForKey:@"province"]; NSString *belong = [NSString stringWithFormat:@"%@ · %@",province,city]; [_resultLB setText:belong]; }); }else{ NSLog(@"未查到信息...."); } NSLog(@"请求成功... %@",result); } }]; //开始任务 [sessionTask resume]; }
相关文章推荐
- IOS 内部测试与开发账号
- iOS下的RSA加密方法
- 直播时代--IOS直播客户端SDK,美艳直播【开源】
- iOS 运行时机制runTime
- 找出程序中的bug——调试
- iOS学习资料
- iOS SDWebImage的原理以及使用流程
- iOS 保持界面流畅的技巧
- 小轮子 ios 获取语言
- IOS开发之运行时
- 直播时代--IOS直播客户端SDK,美颜直播【开源】
- 数据持久化
- iOS 3D Touch 简述
- IOS关于tableview自动下移
- 静态链接库
- 如何学习ios开发
- iOS经典讲解之NSTimer、CADisplayLink、GCD三种定时器的使用
- ios 干掉配置文件
- IOS View 背景颜色渐变--简单级别
- IOS 文字轨迹path