Search code examples
iosnsurl

iOS - build email URL without parsing


I want to build an email URL using some class (NSURL or similar) BUT I do not want the overhead of parsing a string. I want to be able to specify the scheme (mailto in this case) and the address ([email protected] in this case.)

I've tried this code:

NSString *address = @"[email protected]";
NSString *scheme = @"mailto";

NSURL *url = [[NSURL alloc] initWithScheme:scheme host:address path:@"/"];
NSLog(@"test2: %@", [url absoluteString]);

but it outputs:

mailto://[email protected]/

which isn't even a valid email URL.

What are my options?

p.s. please don't suggest using NSDataDetector because it is even more expensive than the usual kind of string parsing.


Solution

  • Assuming you do have purely the email address and no other paraphernalia, the solution is simple:

    - (NSURL *)mailtoURLWithEmailAddress:(NSString *)address;
    {
      address = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
      NSURL *result = [NSURL URLWithString:[@"mailto:" stringByAppendingString:address]];
      return result;
    }
    

    Adding percent escapes is important should there be any chance that somebody might specify an address outside of the ASCII characters, or include one of the reserved URL characters.

    For a more capable solution, see KSMailtoURLs in my KSFileUtilities repository. It adds:

    • Handling of strings that include the recipient's name, as well as address
    • Encoding of email subject line etc.