Country Codes to Plist
In one of my projects I needed all country codes and their names.
I used this site:
http://countrycode.org/
This magic :) HTML/XML parse framework:
https://github.com/topfunky/hpple
Here is the code:
NSURL *url = [NSURL URLWithString:@"http://countrycode.org/"];
NSData * data = [NSData dataWithContentsOfURL:url];
TFHpple * doc = [[TFHpple alloc] initWithHTMLData:data];
NSArray *ar = [doc searchWithXPathQuery:@"/html/body/div/div[2]/div/div[2]/table/tbody"];
TFHppleElement *element = [ar objectAtIndex:0];
NSArray *children = [element children];
NSMutableDictionary *countryCodes = [[NSMutableDictionary alloc] init];
for (TFHppleElement *el in children) {
for (TFHppleElement *elm in [el children]) {
TFHppleElement *countryElement = [[[[el children] objectAtIndex:0] children] objectAtIndex:1];
TFHppleElement *codeElement = [[el children] objectAtIndex:4];
NSString *code = [[codeElement text] stringByReplacingOccurrencesOfString:@"\u00a0" withString:@""];
NSString *codeNW = [code stringByReplacingOccurrencesOfString:@" " withString:@""];
NSString *codePlus = [NSString stringWithFormat:@"+%@", codeNW];
[countryCodes setObject:codePlus forKey:[countryElement text]];
}
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Countries.plist"];
// write plist to disk
[countryCodes writeToFile:path atomically:YES];
Written by Ivan Yordanov
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ios
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#