如何使用后臺(tái)提供過來的城市數(shù)據(jù)庫

相信在大家開發(fā)的工程中,免不了要用到城市選擇這個(gè)功能,對(duì)于新手來說,第一反應(yīng)應(yīng)該就是去 git 上搜一下,當(dāng)然我們可以搜索到很多優(yōu)秀的開源城市選擇項(xiàng)目,直接拖進(jìn)項(xiàng)目就可以使用,但是事與愿違,往往我們選擇城市的時(shí)候,需要傳給后臺(tái)一個(gè)城市 id 作為參數(shù),這時(shí)候你會(huì)發(fā)現(xiàn),咦?這個(gè)第三方里選中城市之后返回的是城市名字?。‘?dāng)然也有帶城市 id 的,而且網(wǎng)上也有一定的城市 id 規(guī)范,但是,你能保證網(wǎng)上的規(guī)范和你們后臺(tái)的城市數(shù)據(jù)庫規(guī)范是一致的嗎?我們不能去冒這個(gè)風(fēng)險(xiǎn),所以我們還是要用后臺(tái)提供給我們的城市數(shù)據(jù)庫文件來用,有可能是 db、json、txt等等的格式,我們沒有辦法直接拿過來用,這時(shí)候就需要我們把這些文件轉(zhuǎn)換成我們所需要的文件,大多數(shù)是轉(zhuǎn)換成 plist 文件,這里我也就簡(jiǎn)單的舉個(gè)例,把后臺(tái)給我的 json 城市數(shù)據(jù)庫文件轉(zhuǎn)換成我所需要的城市選擇 plist 文件,讓我們開始,


首先,我們需要拿到文件,拖進(jìn)自己的項(xiàng)目,這里我放進(jìn)一個(gè) bundle 中

上代碼:

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

//gbk編碼 如果txt文件為utf-8的則使用NSUTF8StringEncoding
//NSStringEncoding gbk = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
//定義字符串接收從 json 文件讀取的內(nèi)容
NSString *str = [[NSString alloc] initWithContentsOfFile:plistPath encoding:NSUTF8StringEncoding error:nil];

//將字符串轉(zhuǎn)為nsdata類型
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

//將nsdata類型轉(zhuǎn)為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];

// 最后再從本地將數(shù)據(jù)從本地取出來 看下是否正確
NSDictionary *dic = [[NSDictionary alloc] initWithContentsOfURL:[NSURL fileURLWithPath:filename]];
NSLog(@"%@",dic);

好了,上面的就是把后臺(tái)給你的城市數(shù)據(jù)庫文件轉(zhuǎn)換成了一個(gè) plist 文件,當(dāng)然后臺(tái)有可能是給你的 txt、db 之類的文件,原理都一樣

but,到這里我們會(huì)想:那旁邊還有 ABCD...的索引啊,我還想根據(jù)索引來把城市拼音首字母來分類起來,這時(shí)候我們就需要來做一個(gè)帶有索引的城市選擇 plist,長話短說

上代碼!:

// 獲取剛才已經(jīng)轉(zhuǎn)成功的城市數(shù)據(jù),用可變數(shù)組保存
NSMutableArray * mutableDict  =[NSMutableArray arrayWithArray:(NSArray *)dic];

// 這一步是關(guān)鍵,這一步就是把所有城市遍歷一遍,然后把首字母項(xiàng)目相同的城市歸類到一個(gè)索引值下,createCharacter方法在下面會(huì)給出
NSDictionary * resultDic = [self createCharacter:mutableDict];

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

到了這一步基本上算是已經(jīng)完成了,但是我們知道 字典是無序的,所以這里面的索引值也是無序的,我們需要對(duì)其進(jìn)行排序,當(dāng)然就是簡(jiǎn)單的排序及循環(huán)便利,也貼出來吧

// 新建可變數(shù)組存儲(chǔ)最后的數(shù)據(jù)
NSMutableArray * resultArr = [NSMutableArray array];

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

// 循環(huán)遍歷排好序的索引數(shù)組
for (NSString *headerStr in paixuArr) {
    
    NSMutableDictionary * yuansuDic = [NSMutableDictionary dictionary];
    [yuansuDic setValue:headerStr forKey:@"title"];
    [yuansuDic setValue:resultDic[headerStr] forKey:@"cities"];
    
    [resultArr addObject:yuansuDic];
}

到這里算是完成了一個(gè)帶有正序的索引值的城市 plist 文件,數(shù)據(jù)結(jié)構(gòu)大致是這樣的:

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

// 也可以在最后添加一個(gè) “熱門” 索引
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(@"結(jié)果數(shù)據(jù) : %@ \n 路徑:%@",resultArr,plistFile);







// 這就是上面那個(gè) 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;
}

到這里全部就結(jié)束了,有錯(cuò)誤或者是不妥的地方還希望大神指點(diǎn)出來,謝謝??

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容