0

I'm working on an in-app email function, and right now I have the line [mailer setSubject:@"Someone has sent you a haiku."];. How do I set it so that "Someone" is replaced by the name of the iPhone's owner, and the subject is "John Doe has sent you a haiku"?

Joel Derfner
  • 2,207
  • 6
  • 33
  • 45

3 Answers3

3

As discussed in this post you can't get the user's name since it is a privacy issue. You can ask the user for his or her name in a first time application setup and then store this information. Of course you'd want to provide a way for the user to change it later via a settings view or similar.

You can, however, find the name of the iPhone you are running on and these are typically named like "John's iPhone". So you might find it acceptable to send messages like "John's iPhone has sent you a haiku.". If this works for you, you can get the iPhone's name and insert it into your string as follows:

[mailer setSubject:[NSString stringWithFormat:@"%@ has sent you a haiku.", [[UIDevice currentDevice] name]]];
Community
  • 1
  • 1
torrey.lyons
  • 5,519
  • 1
  • 23
  • 30
  • Thanks! I'll start with this, since I'm trying to make setup/settings as minimal as possible (though that could be just me being a scaredy-cat).... – Joel Derfner Aug 12 '12 at 07:12
  • 1
    Interesting... John's iPhone has sent you a haiku... (note that substring call in my answer!) –  Aug 12 '12 at 07:31
2

Apple's sandbox does not allow you to get email, contact information, etc, about the user of the iPhone. You can probably find a few ways to do it, but they generally will not pass muster if you submit to the store.

You can get the phone's name: [[UIDevice currentDevice] name];

That is a public API at least, and seems to have some success.

Otherwise, you should just ask the user for the name they'd like to use. Its nicer - maybe they want to put a nickname in anyhow.

Adam B
  • 3,775
  • 3
  • 32
  • 42
2
NSString *deviceName = [[UIDevice currentDevice] name]; // John's iPhone
NSRange r = [deviceName rangeOfString:@"'"]; // { 4; 1 }
NSString *user = [deviceName substringToIndex:r.location];

NSString *subject = [NSString stringWithFormat:@"%@ has sent you a haiku", user];

/* Assumes that the device name contains the user's name as the part before an aphostrophe.
 * If this isn't the case, you have to check for something else.
 */
  • Unfortunately this code throws an NSRangeException if the name does not have an apostrophe in it. :) – Adam B Aug 12 '12 at 06:47
  • @AdamB you see the last comment? (I hope so :) –  Aug 12 '12 at 07:31
  • `[[[deviceName componentsSeparatedByString:@"’"][0] componentsSeparatedByString:@"'"][0] componentsSeparatedByString:@" "][0]` works for any device name. – devios1 Oct 13 '13 at 01:17