//实现的功能是 从后台拿到城市的省份以及名称,然后保存在本地的沙盒中 在使用的时候再拿出来用。
步骤1
//向后台请求数据
//忽略缓存 [RequestTools postJSONWithUrl:G.YB_GetZoneList parameters:@{} success:^(id responseObject) { NSError *error = nil; NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error]; if (error) { NSLog(@"json error:%@",error); } else { if (![dic[@"code"] isEqualToString:@"GOOD"]) { return; } if (![[dic objectForKey:@"content"] isKindOfClass:[NSNull class]]) { //对数据进行解析 NSArray *provinces = [dic objectForKey:@"content"]; if (provinces.count > 0) { //重要代码 [[AccountManager shareManager] cacheCitiesInfomation:provinces]; _locationArray = [[AccountManager shareManager] getCitiesInfomation]; } } } } fail:^(id obj) { NSLog(@"error:%@",obj); }];
步骤二:将解析到到的数据存起来
///缓存地区信息 - (void)cacheCitiesInfomation:(NSArray *)provincesDic{ NSString *citiesPath = [self getPathWithFileName:@"cities.data"]; [provincesDic writeToFile:citiesPath atomically:YES]; }
- (NSString *)getPathWithFileName:(NSString *)fileName{ NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; return [path stringByAppendingPathComponent:fileName]; }
步骤三:从文件中读取信息
///读取地区信息 - (NSArray *)getCitiesInfomation{ NSString *citiesPath = [self getPathWithFileName:@"cities.data"]; NSArray *provincesDic = [[NSArray alloc] initWithContentsOfFile:citiesPath]; if (provincesDic==nil || provincesDic.count==0) { return nil; } NSMutableArray *provinces = [NSMutableArray array]; for (NSDictionary *proDic in provincesDic) { FCZoneProvince *province = [[FCZoneProvince alloc] init]; province.provinceName = proDic[@"provinceName"]; //某一省下的所有市 NSArray *citiesDic = proDic[@"cities"]; NSMutableArray *cities = [NSMutableArray array]; for (NSDictionary *cityDic in citiesDic) { FCZoneCity *city = [[FCZoneCity alloc] init]; city.cityName = cityDic[@"cityName"]; //某一城市下的所有区 NSArray *countriesDic = cityDic[@"counties"]; NSMutableArray *coutries = [NSMutableArray array]; for (NSDictionary *countryDic in countriesDic) { FCZoneCountry *country = [[FCZoneCountry alloc] init]; country.countryName = countryDic[@"countyName"]; if ([country.countryName isEqualToString:@"市辖区"]) { continue; } [coutries addObject:country]; } city.countries = coutries; [cities addObject:city]; } province.cities = cities; [provinces addObject:province]; } return provinces; }
这样就获得了 provinces and cities
在这里我只是提供一个这样的思路,有了思路估计很快就可以上手了吧。
时间: 2024-11-05 12:27:14