标签:
1 // 2 // MyNetworkService.m 3 // 04-天气预报 4 // 5 6 #import "MyNetworkService.h" 7 8 #define BASEURL @"http://www.weather.com.cn" 9 10 @implementation MyNetworkService 11 12 + (void)requestDataWithURL:(NSString *)urlString HTTPMethod:(NSString *)method params:(NSMutableDictionary *)params completionHandle:(void (^)(id result , NSURLResponse *response , NSError *error))completionHandle { 13 14 15 //1.拼接URL 16 NSString *requestURLString = [BASEURL stringByAppendingString:urlString]; 17 18 //2.构造URL 19 NSURL *url = [NSURL URLWithString:requestURLString]; 20 21 22 //3.创建网络请求 23 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 24 25 request.HTTPMethod = method; 26 27 //4.请求参数 key1=value1&key2=value2&key3=value3 28 NSMutableString *paramStr = [NSMutableString string]; 29 30 for (NSInteger i = 0; i < params.count; i++) { 31 NSArray *keys = [params allKeys]; 32 NSString *key = keys[i]; 33 NSString *value = params[key]; 34 35 [paramStr appendFormat:@"%@=%@", key, value]; 36 //如果是最后一个键值对,则不加& 37 if (i < params.count - 1) { 38 [paramStr appendFormat:@"&"]; 39 } 40 41 } 42 43 //如果为GET请求,则请求参数拼接在URL后面 44 if ([method isEqualToString:@"GET"]) { 45 46 //http://www.baidu.com 47 //http://www.baidu.com?key1=value1 48 NSString *seperate = url.query ? @"&" : @"?"; 49 NSString *newUrlString = [NSString stringWithFormat:@"%@%@%@", requestURLString, seperate,paramStr]; 50 51 //重新设置加入了请求参数的URL 52 request.URL = [NSURL URLWithString:newUrlString]; 53 54 55 56 } 57 //如果为POST请求,则请求参数放到请求体中 58 else if ([method isEqualToString:@"POST"]) { 59 60 request.HTTPBody = [paramStr dataUsingEncoding:NSUTF8StringEncoding]; 61 } 62 63 //5.创建session 64 NSURLSession *session = [NSURLSession sharedSession]; 65 66 NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { 67 68 //判断是否请求成功,成功才解析JSON,并回到主线程更新UI 69 if (!error) { 70 //解析JSON 71 NSJSONSerialization *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 72 73 74 dispatch_async(dispatch_get_main_queue(), ^{ 75 completionHandle(json, response, error); 76 }); 77 78 } 79 80 81 }]; 82 83 [task resume]; 84 85 } 86 87 88 @end
// // MyNetworkService.h // 04-天气预报 // #import <Foundation/Foundation.h> @interface MyNetworkService : NSObject + (void)requestDataWithURL:(NSString *)urlString HTTPMethod:(NSString *)method params:(NSMutableDictionary *)params completionHandle:(void (^) (id result, NSURLResponse *response, NSError *error))completionHandle; @end
1 // 2 // ViewController.m 3 // 04-天气预报 4 // 5 #import "ViewController.h" 6 #import "MyNetworkService.h" 7 8 9 @interface ViewController () 10 11 @end 12 13 @implementation ViewController 14 { 15 //创建字典保存城市数据。创建数组保存城市名。 16 NSDictionary *_data; 17 NSArray *_cities; 18 19 } 20 21 - (void)viewDidLoad { 22 [super viewDidLoad]; 23 24 //通过plist文件获取城市数组。 25 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"cityCode" ofType:@"plist"]; 26 _data = [NSDictionary dictionaryWithContentsOfFile:filePath]; 27 _cities = [_data allKeys]; 28 29 30 //刚进入时请求第一个城市的网络数据 31 [self pickerView:self.pickerView didSelectRow:0 inComponent:0]; 32 33 34 35 } 36 37 38 - (void)refreshUI:(NSDictionary *)result { 39 //大字典里key:weatherinfo 40 //value:小字典。 41 NSDictionary *weatherinfo = [result objectForKey:@"weatherinfo"]; 42 43 44 NSString *windLevel = weatherinfo[@"WS"]; 45 NSString *temp = weatherinfo[@"temp"]; 46 NSString *city = weatherinfo[@"city"]; 47 NSString *windDirection = weatherinfo[@"WD"]; 48 NSString *time = weatherinfo[@"time"]; 49 50 _tempLabel.text = [NSString stringWithFormat:@"温度:%@",temp]; 51 _windLevelLabel.text = [NSString stringWithFormat:@"风级:%@",windLevel]; 52 _cityLabel.text = [NSString stringWithFormat:@"城市:%@",city]; 53 _windDirLabel.text = [NSString stringWithFormat:@"风向:%@",windDirection]; 54 _publicTimeLabel.text = [NSString stringWithFormat:@"发布时间:%@",time]; 55 56 } 57 58 59 60 #pragma mark - UIPickeView Delegate 61 62 //列数 63 - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { 64 65 return 1; 66 } 67 68 //根据城市个数获取行数 69 - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { 70 return _cities.count; 71 } 72 73 //每行的标题 74 - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { 75 NSString *cityName = _cities[row]; 76 return cityName; 77 } 78 79 //选中某行时调用的协议方法 80 - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { 81 82 //网络加载方法 83 [self loadWeatherWithCityIndex:row]; 84 85 } 86 87 88 89 - (void)loadWeatherWithCityIndex:(NSInteger)index { 90 91 //获取被选中的城市名称 92 NSString *cityName = _cities[index]; 93 94 //获取城市id 95 NSString *cityID = _data[cityName]; 96 97 98 //根据城市ID拼接URL 99 NSString *urlString = [NSString stringWithFormat:@"/data/sk/%@.html", cityID]; 100 101 102 [MyNetworkService requestDataWithURL:urlString HTTPMethod:@"GET" params:nil completionHandle:^(id result, NSURLResponse *response, NSError *error) { 103 104 NSLog(@"result:%@", result); 105 106 [self refreshUI:result]; 107 108 }]; 109 110 111 } 112 113 114 115 116 @end
标签:
原文地址:http://www.cnblogs.com/foreveriOS/p/5433105.html