//同步请求 //创建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:10]; //发送请求 NSData* data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //处理数据 NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:data options:0 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:10]; //发送请求 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if (data) { //处理数据 NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; //NSLog(@"%@",dic); NSDictionary* dicsk=dic[@"result"]; NSDictionary* temp=dicsk[@"today"]; NSLog(@"城市==%@",temp[@"city"]); } if (connectionError) { NSLog(@"Error"); } }];