Getting the iPhone User Name

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:

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:

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.

  1. 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]

  2. 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 :)

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

  4. 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.

  5. 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.

Comments are closed.