Brandon
Brandon

Reputation: 2171

iOS Calling Phone Number from NSUserDefaults

I am trying to store a phone number as an NSString in NSUserDefaults. For some reason the code below does not work. The code works if I do not use a variable, but I cannot get it to work. Does anyone have any ideas why?

NSString *savedPhone = [[NSUserDefaults standardUserDefaults]
                        stringForKey:@"savedPhone"];

NSString *callNumber = [NSString stringWithFormat:@"%@%@",@"tel://",savedPhone];

NSURL *myURL = [NSURL URLWithString:callNumber];
[[UIApplication sharedApplication] openURL:myURL];

Please let me know if anyone has any ideas. Thank you!

Upvotes: 1

Views: 351

Answers (4)

Irshad Mansuri
Irshad Mansuri

Reputation: 407

  NSString *number = YOUR-NUMBER;       
  NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"telprompt:%@",number]];

 [[UIApplication sharedApplication] openURL:url]; 

Try with this code, it will navigate back to your app after finished call

Upvotes: 0

Nishant B
Nishant B

Reputation: 2897

You can achieve with below code:

NSUserDefaults *objUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *savedPhone = [objUserDefaults objectForKey:@"savedPhone"];
[self callNumber:savedPhone];

Then add below function:

-(void)callNumber:(NSString *)pstrContactNo
{
    NSString *strDeviceModel = [UIDevice currentDevice].model;
    if(![strDeviceModel isEqualToString:@"iPhone"])
    {
            UIAlertView *objAlertMsg = [[UIAlertView alloc] initWithTitle:@""
                                                       message:@"Calling is not supported in this device."
                                                      delegate:nil
                                             cancelButtonTitle:@"OK"
                                             otherButtonTitles:nil];
       [objAlertMsg show];
       [objAlertMsg release];
    }
    else
    {
        pstrContactNo = [NSString stringWithFormat:@"tel:%@",pstrContactNo];
        NSString *strDialedContact = [pstrContactNo stringByReplacingOccurrencesOfString:@" " withString:@""];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strDialedContact]];
    }
}

This will resolve your issue.

Cheers!

Upvotes: 0

Stas
Stas

Reputation: 9935

Change your callNumber like this: NSString *callNumber = [NSString stringWithFormat:@"tel:%@",savedPhone];

Upvotes: 0

Oleg
Oleg

Reputation: 3014

Change your URL format (remove //)

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:2135554321"]];

Upvotes: 1

Related Questions