简体   繁体   中英

How do I insert the registered owner's name into a string for an email subject?

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"?

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]]];

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.

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.
 */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM