如何使用后台提供过来的城市数据库

相信在大家开发的工程中,免不了要用到城市选择这个功能,对于新手来说,第一反应应该就是去 git 上搜一下,当然我们可以搜索到很多优秀的开源城市选择项目,直接拖进项目就可以使用,但是事与愿违,往往我们选择城市的时候,需要传给后台一个城市 id 作为参数,这时候你会发现,咦?这个第三方里选中城市之后返回的是城市名字啊!当然也有带城市 id 的,而且网上也有一定的城市 id 规范,但是,你能保证网上的规范和你们后台的城市数据库规范是一致的吗?我们不能去冒这个风险,所以我们还是要用后台提供给我们的城市数据库文件来用,有可能是 db、json、txt等等的格式,我们没有办法直接拿过来用,这时候就需要我们把这些文件转换成我们所需要的文件,大多数是转换成 plist 文件,这里我也就简单的举个例,把后台给我的 json 城市数据库文件转换成我所需要的城市选择 plist 文件,让我们开始,


首先,我们需要拿到文件,拖进自己的项目,这里我放进一个 bundle 中

上代码:

// 获取原始城市文件
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@".bundle/custom_city_json" ofType:@"json"];

//gbk编码 如果txt文件为utf-8的则使用NSUTF8StringEncoding
//NSStringEncoding gbk = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
//定义字符串接收从 json 文件读取的内容
NSString *str = [[NSString alloc] initWithContentsOfFile:plistPath encoding:NSUTF8StringEncoding error:nil];

//将字符串转为nsdata类型
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

//将nsdata类型转为NSDictionary
NSDictionary *pDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

// 获取沙盒路径
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *plistPath1 = [paths objectAtIndex:0];

//得到完整的文件名
NSString *filename=[plistPath1 stringByAppendingPathComponent:@"custom_city.plist"];

// 写入文件
[pDic writeToFile:filename atomically:YES];

// 最后再从本地将数据从本地取出来 看下是否正确
NSDictionary *dic = [[NSDictionary alloc] initWithContentsOfURL:[NSURL fileURLWithPath:filename]];
NSLog(@"%@",dic);

好了,上面的就是把后台给你的城市数据库文件转换成了一个 plist 文件,当然后台有可能是给你的 txt、db 之类的文件,原理都一样

but,到这里我们会想:那旁边还有 ABCD...的索引啊,我还想根据索引来把城市拼音首字母来分类起来,这时候我们就需要来做一个带有索引的城市选择 plist,长话短说

上代码!:

// 获取刚才已经转成功的城市数据,用可变数组保存
NSMutableArray * mutableDict  =[NSMutableArray arrayWithArray:(NSArray *)dic];

// 这一步是关键,这一步就是把所有城市遍历一遍,然后把首字母项目相同的城市归类到一个索引值下,createCharacter方法在下面会给出
NSDictionary * resultDic = [self createCharacter:mutableDict];

// 看一下生成了什么东西
CLog(@"mutableDict: %@ \n resultDic : %@",mutableDict,resultDic);

到了这一步基本上算是已经完成了,但是我们知道 字典是无序的,所以这里面的索引值也是无序的,我们需要对其进行排序,当然就是简单的排序及循环便利,也贴出来吧

// 新建可变数组存储最后的数据
NSMutableArray * resultArr = [NSMutableArray array];

// all key 里面是索引值,我们进行排序
NSArray * paixuArr = [[resultDic allKeys] sortedArrayUsingSelector:@selector(compare:)];

// 循环遍历排好序的索引数组
for (NSString *headerStr in paixuArr) {
    
    NSMutableDictionary * yuansuDic = [NSMutableDictionary dictionary];
    [yuansuDic setValue:headerStr forKey:@"title"];
    [yuansuDic setValue:resultDic[headerStr] forKey:@"cities"];
    
    [resultArr addObject:yuansuDic];
}

到这里算是完成了一个带有正序的索引值的城市 plist 文件,数据结构大致是这样的:

(
  {
     title : "A"
     cities: (
                {
                   cityid : 567464
                   name : 阿贝
                },
                {
                   cityid : 342422
                   name : 鞍山
                }
              )
  },
  {
     title : "B"
     cities: (
                {
                   cityid : 110100
                   name :  北京
                },
                {
                   cityid : 345332
                   name : 保定
                }
              )
  },
)

// 也可以在最后添加一个 “热门” 索引
NSMutableDictionary * yuansuDic = [NSMutableDictionary dictionary];
[yuansuDic setValue:@"热门" forKey:@"title"];
[yuansuDic setValue:@[@{@"name" : @"我是热门城市",@"city_id" : @"888888"}] forKey:@"cities"];
[resultArr insertObject:yuansuDic atIndex:0];


// 保存到文件
NSArray * pathAll = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * pathDetail = [pathAll objectAtIndex:0];
NSString * plistFile = [pathDetail stringByAppendingPathComponent:@"custom_city_group.plist"];
[resultArr writeToFile:plistFile atomically:YES];

// 好了  最后来看下我们得成果
CLog(@"结果数据 : %@ \n 路径:%@",resultArr,plistFile);







// 这就是上面那个 createCharacter 方法
- (NSDictionary *)createCharacter:(NSMutableArray *)strArr
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    for (NSDictionary *stringdict in strArr) {
            NSString *string = stringdict[@"name"];
            NSString *cityid = stringdict[@"city_id"];
        if ([string length]) {
            NSMutableString *mutableStr = [[NSMutableString alloc]initWithString:string];
        
        if (CFStringTransform((__bridge CFMutableStringRef)mutableStr,0,kCFStringTransformMandarinLatin,NO)) {
        }
        if (CFStringTransform((__bridge CFMutableStringRef)mutableStr,0,kCFStringTransformStripDiacritics,NO)) {
            NSString *str = [NSString stringWithString:mutableStr];
            str = [str uppercaseString];
            
            NSMutableArray *subArray = [dict objectForKey:[str substringToIndex:1]];
            if (!subArray) {
                subArray = [NSMutableArray array];
                [dict setObject:subArray forKey:[str substringToIndex:1]];
            }
            
            NSDictionary * dci = [NSDictionary dictionaryWithObjectsAndKeys:string,@"name",cityid,@"city_id", nil];
            [subArray addObject:dci];
            
          }
      }
  }
return dict;
}

到这里全部就结束了,有错误或者是不妥的地方还希望大神指点出来,谢谢😄

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容