Created
March 20, 2014 22:34
-
-
Save blindsey/9675447 to your computer and use it in GitHub Desktop.
MKLocalSearch reverse zip code lookup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.m | |
// Ziptastic | |
// | |
// Created by Ben Lindsey on 3/20/14. | |
// Copyright (c) 2014 Ben Lindsey. All rights reserved. | |
// | |
#import "ViewController.h" | |
#import <MapKit/MapKit.h> | |
@interface ViewController () | |
@property (weak, nonatomic) IBOutlet UITextField *zipField; | |
@property (weak, nonatomic) IBOutlet UILabel *resultLabel; | |
@property (strong, nonatomic) IBOutlet NSRegularExpression *regex; | |
@end | |
@implementation ViewController | |
- (void)viewDidLoad | |
{ | |
[super viewDidLoad]; | |
self.zipField.delegate = self; | |
} | |
- (void)didReceiveMemoryWarning | |
{ | |
[super didReceiveMemoryWarning]; | |
// Dispose of any resources that can be recreated. | |
} | |
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string | |
{ | |
return [string length] == 0 || [[[NSNumberFormatter alloc] init] numberFromString:string] != nil; | |
} | |
- (BOOL)textFieldShouldReturn:(UITextField *)textField | |
{ | |
[textField resignFirstResponder]; | |
return YES; | |
} | |
- (void)textFieldDidEndEditing:(UITextField *)textField | |
{ | |
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init]; | |
request.naturalLanguageQuery = textField.text; | |
MKLocalSearch *search = [[MKLocalSearch alloc] initWithRequest:request]; | |
[search startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) { | |
self.resultLabel.text = @"Zip Lookup Failed"; | |
if ([response.mapItems count] > 0) { | |
MKMapItem *item = response.mapItems[0]; | |
NSString *name = item.name; | |
NSArray *matches = [self.regex matchesInString:name options:0 range:NSMakeRange(0, [name length])]; | |
if ([matches count] == 1) { | |
NSTextCheckingResult *match = matches[0]; | |
NSLog(@"City=%@ State=%@ Zip=%@", [name substringWithRange:[match rangeAtIndex:1]], [name substringWithRange:[match rangeAtIndex:2]], [name substringWithRange:[match rangeAtIndex:3]]); | |
self.resultLabel.text = name; | |
} | |
} | |
}]; | |
} | |
- (NSRegularExpression *)regex | |
{ | |
if (!_regex) { | |
NSError *error = NULL; | |
_regex = [NSRegularExpression regularExpressionWithPattern:@"^(.*),\\s*(\\w{2})\\s*(\\d{5})" options:0 error:&error]; | |
if (error) NSLog(@"Regex error: %@", error); | |
} | |
return _regex; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment