Check email with NSDataDetector

EDIT:

my answer has been accepted in 2012 and is pretty outdated. Please read please this one instead.

Original post:

In apple documentation, it seems that recognised types does not include email : http://developer.apple.com/library/IOs/#documentation/AppKit/Reference/NSTextCheckingResult_Class/Reference/Reference.html#//apple_ref/c/tdef/NSTextCheckingType

So I suggest you to use a Regexp. It would be like :

NSString* pattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]+";

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
if ([predicate evaluateWithObject:@"[email protected]"] == YES) {
  // Okay
} else {
  // Not found
}

if (result.resultType == NSTextCheckingTypeLink)
{
    if ([result.URL.scheme.locaseString isEqualToString:@"mailto"])
    {
        // email link
    }
    else
    {
        // url
    }
}

Email address falls into NSTextCheckingTypeLink. Simply look for "mailto:" in the URL found and you will know it is an email or URL.


Try following code, see if it works for you :

NSString * mail = [email protected]
NSDataDetector * dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSTextCheckingResult * firstMatch = [dataDetector firstMatchInString:mail options:0 range:NSMakeRange(0, [mail length])];
BOOL result = [firstMatch.URL isKindOfClass:[NSURL class]] && [firstMatch.URL.scheme isEqualToString:@"mailto"];