Under the Bridge

Snippet: Phone number

Quick one liner for you today: Ever wondered how to retrieve the user’s phone number programmatically? Well, here’s the trick:

   id number = [[NSUserDefaults standardUserDefaults] objectForKey:@”SBFormattedPhoneNumber”];

   NSLog(@”user phone number is %@”, number);

Run that and you’ll get output like
user phone number is 1 (555) 555-5555

Beats the heck out of asking the user to select their own address book entry or something like that, doesn’t it now?

h/t: iphonesdk!

7
  • tim

    how do i enter this info into my iphone?

  • Gustavo

    Does it work with iphone firmware 2.1? I reading an empty string.

  • http://www.alexcurylo.com Alex

    Just tried it again with my 2.2.1 firmware phone and it works exactly as when I posted this.

    Since I’ve never entered the phone number explicitly anywhere, I don’t have any obvious explanation why yours would act any different, sorry.

  • http://gregcrisp.us Greg

    I just ran this code as-is on OS 2.2.1.

    It works as expected when run on the device, and returns my phone number with the full international dialing codes [ 1 in my case].

    When run on the simulator, the value in number is a null string, so it only works on an actual iPhone device.

    I did not test it on an iPod Touch.

  • http://gregcrisp.us Greg

    Ran this code on a different device this week, and got a null value instead of the number.

    On further research, it appears that the number returned by this code snippit is the number that is set up in iTunes for the device.

    If you didn’t enter the iPhone’s in iTunes at device activation, or perhaps [as in my case] if the default value wasn’t the iPhone’s number and you clicked OK anyway, such that iTunes doesn’t list the phone number when your iPhone is plugged in, this code will return a null string.

  • Narendraomshiv1234

    i used your code and install my app on my device but it’s giving null not my sim phone number

  • hakaji

    me too