jsanmtosj
jsanmtosj

Reputation: 563

How to call a phone from a number entered in a UITextField?

I'd like to make a button call a phone number entered by the user inside the text field. I have a code but it doesn't work.

NSString * phoneNumber = [NSString stringWithFormat:@"%@%@", @"tel://", phoneNumber.text];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];

Anyone has a similar approach to this? Thanks.

Upvotes: 0

Views: 346

Answers (2)

Johan Kool
Johan Kool

Reputation: 15927

See my answer to another question for some sample code to handle cases with invalid input.

Basically you do this:

NSString *cleanedString = [[phoneNumber componentsSeparatedByCharactersInSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789-+()"] invertedSet]] componentsJoinedByString:@""];
NSString *escapedPhoneNumber = [cleanedString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *telURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", escapedPhoneNumber]];

Update: I noticed that the string you created shares the some name ("phoneNumber") as the text field from which you try to get the text. You may want to rename either of those two.

Upvotes: 0

sudo rm -rf
sudo rm -rf

Reputation: 29524

I think it's tel: instead of tel://. See this Apple document. Try giving this a shot:

NSString *pn = [@"tel:" stringByAppendingString:phoneNumber.text];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:pn]];

Upvotes: 2

Related Questions