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!

Alex | November 14, 2008
  • tim December 25, 2008 at 2:45 am
    how do i enter this info into my iphone?
  • Gustavo February 5, 2009 at 1:37 am
    Does it work with iphone firmware 2.1? I reading an empty string.
  • Alex February 5, 2009 at 11:31 am
    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.
  • Greg June 19, 2009 at 7:36 am
    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.
  • Greg June 26, 2009 at 7:26 am
    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 May 18, 2012 at 4:15 am
    i used your code and install my app on my device but it's giving null not my sim phone number
  • hakaji March 22, 2013 at 2:46 am
    me too

Leave a Reply