Getting the iPhone User Name

April 16, 2009

The original tip I wrote (shown below) does retrieve the user name, however, giving its undocumented status as well as the returning a string with punctuation removed, the approach suggested by Pascal in the comment section is much better:

[[UIDevice currentDevice] name];

When running this code from my device it returns "John’s iPhone" and when running from the simulator, it returns "iPhone Simulator." Much better. Thanks Pascal.

[Original post follows...]

Here’s a few lines of code to get the name of the owner tied to an iPhone:

NSArray *nameArray = [[NSHost currentHost] names];
NSString *user = [nameArray objectAtIndex:0];

You will need to do a little additional formatting of the NSString if you need to display the returned value, as the result replaces spaces and punctuation – "John’s iPhone" is returned as "John-s-iPhone". When I ran this on the simulator, the output I received was : john-3.local.

I did receive compiler warnings that the methods +currentHost and -names were not found. Given the warning, I’m not sure of Apple’s intention to make this available (or not) as a publicly accessible API, however, everything seemed to work as expected without the need to include any additional header files or linking in additional libraries/frameworks.

6 comments

Why not just using [[UIDevice currentDevice] name] to get the name of the iPhone (since this seems to be the base of the currentHostname.

This is documented:

http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIDevice_Class/Reference/UIDevice.html#//apple_ref/occ/instp/UIDevice/name

Pascal

by Pascal on Apr 17, 2009. Reply #

This is an awesome tip John – will play around with it. Surely this should be a publicly accessible API if not it should be in 3.0.

[Thanks to Pascal, we now know there is a publicly accessible approach :) john]

by iphone app developer on Apr 17, 2009. Reply #

When you say User Name in your post title, I thought you meant this:

char* login = getlogin();
NSString *nsLogin = [NSString stringWithCString:login];

You’re getting the device’s hostname. You can modify that to whatever you like. It doesn’t have to have the person’s name in it. Mine, for example, is “Alien iPhone”. My code above is getting the Unix username.

Nice tip though :)

by Ray Scott on Apr 17, 2009. Reply #

Ray, your Code dosen’t work on iPhone, it just gives “mobile”. It works in the simulator as expected.

by Tobias Klonk on Apr 17, 2009. Reply #

His code is perfectly accurate. On the simulator it will return the username of the user running the simulator process. The username the iPhone uses to run apps is mobile. All code is fine.

by Eoin on Apr 28, 2009. Reply #

This is an Great tip John, will surely check around with it. Surely this should be a publicly accessible API if not it should be in 3.1 indeed.

by iPhone Developer on Oct 21, 2009. Reply #

Leave a Comment