Efficient way to validate state and zip code - ios

I'm looking for a easy way to validate state and zip code (U.S Only). Obviously there are many ways that this can be done. I have zip code:
- (BOOL)validateZipCode
{
bool returnValue = false;
NSString *zipcodeExpression = #"^[0-9]{5}(-/d{4})?$"; //U.S Zip ONLY!!!
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:zipcodeExpression options:0 error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:ZipCodeTextField.text options:0 range:NSMakeRange(0, [ZipCodeTextField.text length])];
if (match)
{
returnValue = true;
}
return returnValue;
}
Would it be common to just have a list of all the states and abbreviations and just compare the user input to check for a match? This just seems like a lot.
I guess I'm looking for alternatives. I also heard of some frameworks that when a user inputs a zip code, the city and state are then auto generated. Does anyone know of any alternatives like this?

I simple plist file in your app preloaded with the state names and abbreviations is trivial enough. Your regular expression will validate that a string represents a valid zip code.
If you need to actually verify that the zip code and the state match, that will take a lot more data.
A quick google search should reveal some web services you may be able to use to get a state from a zip code. Zip codes change (at least new ones added) on occasion. You may be able to provide a state/zip code database file in your app. But you will need a way to update the database once in a while without needing to submit an update of your app.
Update: A quick look at the Wikipedia Zip Code page reveals that some zip codes span more than one state.

Related

Forcing Voiceover to read particular word (homographs)

I want to use the word "live" (l-eye-v) for an event on now rather than "live" (l-i-v) as in "will she live". Is there any way to force this?
The answers to VoiceOver accessibility label for Touch ID are fairly relevant to this question and suggest that the answer is no, there is nothing that can be done to force it. This question title is much more generally applicable and searchable so I think it is a useful addition even if answers do link there. There are also aspects of the linked question that are applicable only to a particular situation.
There is also VoiceOver pronunciation issue: "Live" "ADD" which discusses the specific case of "Live" too worth a read if you find this page now.
A good way to implement this is to override the accessibilityLabel getter property. This way you don't have to track both strings separately, just have a dictionary of words that need phonetic replacement. So for example, if your object were a UILabel, you could do something like this:
-(NSString*)accessibilityLabel {
NSMutableString* mutableResult = [NSMutableString new];
for (NSString* word in [self.text componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#" \t\n"]]) {
if ([word isInDictionary]) {
[mutableResult appendFormat:#" %#", [word phoneticReplacement]];
} else {
[mutableResult appendFormat:#" %#", word];
}
}
return mutableResult;
}
In these cases, what I usually do is just add a separate accessibility string (as opposed to using the text displayed to the user) that contains the word phonetically. So try something like lyve/lieve. Text to speech is a complicated process and requires a lot of AI to work properly with homonyms.

How to select a sub-string from an NSString using a key word?

I had written a code snippet which writes the contents of a textfield to a file. Unfortunately my code, depending on the OS, writes the file path differently
In Yosemite, The path is
file:///var/folders/qg/....../myfile.txt
While in mountain lion the path is
file://localhost/var/folders/yx....../myfile.txt
I have an API which takes the file path as /var/folder/xx/...../myfile.txt
I was wondering if there is a way to make a substring from /var/.. till the end of the path.
You could do something along the following:
// Lets say pathString is an NSString of the path
NSRange varRange = [pathString rangeOfString:#"/var/"];
NSString *correctPath = [pathString substringFromIndex:varRange.location];
In the above example, you use NSString's instance method rangeOfString: to receive the range of the wanted substring, which in this case is /var/, and store it into a range variable.
Then you create a new NSString variable, using the original pathString, with the use of the instance variable substringFromIndex, which returns a new substring, which start at the index you choose, and ends at the end of the string (which you provide the range location we've received, to identify where /var/ begins).
Good luck mate.
If file path is store in NSString *yourPathString, then
NSString *resultString= [yourPathString substringFromIndex:[yourPathString rangeOfString:#"/var"].location]];
NSLog(#"Final result : %#", resultString);
Try this code, hope it helps.
Depending on how you're calling your resource, how it needs to be saved, and what that API is looking for, you'll want to use NSURL methods, not strings. Specifically, it sounds like you'll be most interested in using absolutePath, relativePath, resourceIdentifierand pathComponents
I would recommend reading the URL Loading System guide by Apple or NSHipster's article for a more human readable answer.

Extract facebook pages from url [ios]

my problem is very minor but I can't resolve it.
I have 2 facebook url's:
http://www.facebook.com/pages/Name_Of_Page/ID_OF_PAGE
http://www.facebook.com/Name_Of_Page
And I need to extract only the name by using NSRegularExpression.
This is my code:
NSRegularExpression* FBregex = [NSRegularExpression regularExpressionWithPattern:#"((http|https)://)?([w]{3}\\.)?(facebook\\.com/(pages/)?)" options:0 error:&error];
NSString *result=[FBregex stringByReplacingMatchesInString:STRING_TO_EVALUATE options:0 range:NSMakeRange(0, [STRING_TO_EVALUATE length]) withTemplate:#""]
I need to remove the ID of the page to be shown. Any ideas?
thanks.
I've not used NSRegularExpressions before, but if it's Perl-Compatible, there are a couple of ways you can get to what you want.
This is a lookbehind method. Lookbehinds do not capture anything, they just mark a position, so the match starts with the character class and ends when it runs into a word boundary.
~(?<=pages/)[-A-Z0-9_.]+\b~i
This is a Forget Everything method. The \K tells the REGEX engine to require the pages/ to be there, but then forget it. So, it has the same effect of starting the capture at the character class and ending when it runs into a word boundary.
~pages/\K[-A-Z0-9_.]+\b~i
Both of these methods will only give you the name of the page.
Here is a demo

YouTube videoID Matching and replacing

I'm completely stumped on this one, and my complete lack of skill with regular expressions doesn't help.
Here is what I'm trying to achieve:
- I have multiple NSStrings that contain the text (and links) from blog posts that I've downloaded from a site online.
- I'm using a UIWebView with an HTML page I create on the fly so that I can have inline images, videos etc.
- The blog posts contain two types of YouTube link -
<iframe src="//www.youtube.com/embed/VIDEOID" height="405" width="720" allowfullscreen="" frameborder="0"></iframe>
and
http://youtu.be/VIDEOID
There are two different types of URL because the blog uses Wordpress and Wordpress has automatic detection for YouTube links, meaning embeds aren't required. Also the first type of embed doesn't work because it relies on the browser being able to request either http or https (hence the lack of it in the URL there), that apparently doesn't work in UIWebViews.
Essentially what I want to do is find the VideoID from both types of URL, then take the existing URL out of the NSString and replace it with the correct embed type with the correct VideoID attached. I also need to keep the rest of the string intact. To top it all off, it needs to work through multiple URLs in the same NSString, as there are an unknown number of videos per post.
This is the code I have so far, but I know it's horribly wrong and I'm not achieving what I want:
NSString *regexToReplaceRawLinks = #"(https?://)?(www\\.)?(youtu\\.be/|youtube\\.com)?(/|/embed/|/v/|/watch\\?v=|/watch\\?.+&v=)([\\w_-]{11})(&.+)?";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexToReplaceRawLinks
options:NSRegularExpressionCaseInsensitive
error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#"<iframe width=\"320\" height=\"180\" src=\"http:\/\/www.youtube.com\/embed\/$1\" frameborder=\"0\" allowfullscreen><\/iframe>"];
NSLog(#"%#", modifiedString);
return modifiedString;
I would be extremely grateful if anyone could point me in the right direction, particularly with the regex's
Assuming // can be the start of your url(as you have shown in your example), you can try this regex:
(?:https?:)?//(?:[^.]*\.)?youtu(?:\.be|be\.com)(?:/|/embed/|/v/|/watch/?\?(?:.+&)?v=)([\w-]{11})
Just escape \ with \\ from above if you need.

Simple (tutorial/blog/explanation) of basic RegEx implementation(searching for a string in another string) in Cocoa XCode?

I have an html code stored in a string. Now I want to extract one of the images from the source code.
I was earlier using REgExKitLite but according to this link http://www.cocoabuilder.com/archive/cocoa/288966-applications-using-regexkitlite-no-longer-being-accepted-at-the-appstore.html , it's suggested not to use REgExKitLite if we want to submit my app to app store.
I just need a very simple implementation to extract one string from another using regEx. Most of the other SO solutions are trying to achieve pretty complex tasks and hence its difficult to understand for a beginner like me.
Even a good tutorial link(about NSRegularExpression implementation) will do. I really dont mind reading it and learning the basics as long as the tutorial is simple and clear. Thnx!
In iOS 4.0+, you can use NSRegularExpression:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"stack(.*).html" options:0 error:NULL];
NSString *str = #"stackoverflow.html";
NSTextCheckingResult *match = [regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
// [match rangeAtIndex:1] gives the range of the group in parentheses
// [str substringWithRange:[match rangeAtIndex:1]] gives the first captured group in this example
You can follow this reference to get more solutions.

Resources