NSURLConnection 异步加载网络数据
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//[self takeRequestUrlWithString:@"http://127.0.0.1/test.json"];
//[self takeRequestUrlWithString:@"http://www.baidu.com"];
}
-(void)takeRequestUrlWithString:(NSString*)str
{
NSURL *url=[NSURL URLWithString:str];
NSURLRequest *request=[NSURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:15];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(!connectionError)
{
NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse*)response;
if (httpResponse.statusCode==200) {
NSError *error=nil;
//返回的要么是字典要么是数组
id needData=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if(error)
{
NSLog(@"JSON 解析出错:%@",error);
}
else{
NSLog(@"模型转换:数据为:%@",needData);
}
}
else
{
NSLog(@"服务器出错 ,错误码:%ld",httpResponse.statusCode);
}
}
else{
NSLog(@"连接错误!!!");
}
}];
}
@end
@interface RYDataModel : NSObject
@property(nonatomic,strong)NSNumber *age;
@property(nonatomic,copy)NSString*name;
@property(nonatomic,strong)NSDictionary*school;
+(instancetype)dataWithDict:(NSDictionary*)dict;
@end
@implementation RYDataModel
+(instancetype)dataWithDict:(NSDictionary*)dict
{
RYDataModel *model=[RYDataModel new];
[model setValuesForKeysWithDictionary:dict];
return model;
}
@end
最新文章
- Stack操作,栈的操作。
- CsvHelper支持List<;T>;
- Taylor定理证明
- JAVA手记 JAVA入门(安装+Dos下运行)
- redis操作
- Sublime Text 使用 Emmet 补全错误问题
- Poj/OpenJudge 1042 Gone Fishing
- C学习-fgets()篇1
- Java的自定义注解使用实例
- MySql分割字符串【存储过程】
- 使用 WeihanLi.Npoi 操作 CSV
- linux 下 mac 地址如何查询
- 解析如何实现微信唤醒默认浏览器下载app教程!
- [转]Angular: Hide Navbar Menu from Login page
- Linux 简介(day1)
- darknet源码解析
- CSS基本知识(慕课网)
- bitnami redmine安装、配置、备份、恢复
- Spring之核心容器bean
- Mysql储存过程8:repeat循环