用 get 同步/异步 方式获取网络数据并输出

时间:2022-11-04 23:02:32
//同步请求
//创建NSString用来存储请求的网址
NSString* str=@"http://v.juhe.cn/weather/index?format=2&cityname=沈阳&key=41cf6f9685a8776dc8384806c262ca0e";
//用UTF8String格式转换成NSURL
NSURL* url=[NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//创建请求
NSURLRequest* request=[[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:];
//发送请求
NSData* data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//处理数据
NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:data options: error:nil];
NSDictionary* dicsk=dic[@"result"];
NSDictionary* temp=dicsk[@"today"];
NSLog(@"城市:%@",temp[@"city"]);
NSLog(@"%@",dicsk);
//异步请求
//创建NSString用来存储请求的网址
NSString* str=@"http://v.juhe.cn/weather/index?format=2&cityname=沈阳&key=41cf6f9685a8776dc8384806c262ca0e";
//用UTF8String格式转换成NSURL
NSURL* url=[NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//创建请求
NSURLRequest* request=[[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:];
//发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (data) {
//处理数据
NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:data options: error:nil];
//NSLog(@"%@",dic);
NSDictionary* dicsk=dic[@"result"];
NSDictionary* temp=dicsk[@"today"];
NSLog(@"城市==%@",temp[@"city"]);
}
if (connectionError) {
NSLog(@"Error");
}
}];