您可以在您的应用程序包中拥有一个包含国家名称和州名列表的 JSON 文件 :) 由于国家和州不会经常更改,因此在您的应用程序包中包含硬编码数据是安全的 :)
假设您将国家/地区数据保存在名为 Country.json 的文件中
你可以通过使用来阅读,
NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"countries" ofType:@"json"]];
NSError *localError = nil;
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&localError];
if (localError != nil) {
NSLog(@"%@", [localError userInfo]);
}
countriesList = (NSArray *)parsedObject;
就是这样 :) 哥们,你有你的国家名单 :)
或
如果您不想自己保存国家/地区,请在使用 GET 请求获取国家/地区列表后,将响应保存在应用程序文档文件夹中的文件中:)
下次从同一个文件中读取数据:)
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = @"countries.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
if ([[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
NSData *data = [NSData dataWithContentsOfFile:fileAtPath];
NSError *localError = nil;
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&localError];
}
else {
//make webservice call fetch the country list and write it to file :)
}
保存整个世界国家列表及其在用户默认值中的资本不是可取的伙伴:) 并且每次从服务器获取它都会延迟向用户显示选择器:)
所以我的建议是在应用程序包中保存一个文件,并在需要数据伙伴时随时阅读:)