views:

198

answers:

4

I have a tableView which has cells with phone numbers. The app is not dialing the numbers though. See the code below

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 if (indexPath.section == 2) {
  UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
  NSString *numberToDial = [NSString stringWithFormat:@"tel:%@", selectedCell.detailTextLabel.text];

  NSLog(@"%@",numberToDial);

  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:numberToDial]];
 }
}

Console ouput: 2010-03-08 01:32:30.830 AIB[1217:207] tel:01 8350098

As you can see, the number goes to the console, but doesn't get dialled. The weird thing is, if I change the last statement to this:

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

the phone dials the number 171 without any issue


The solution to my particular problem is, as suggested below, to remove the spaces from the phone numbers. I achieved this as follows:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {
        UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
        NSMutableString *numberToDial = [NSMutableString stringWithFormat:@"tel:%@", selectedCell.detailTextLabel.text];

        [numberToDial replaceOccurrencesOfString:@" " 
                                      withString:@"" 
                                         options:NSLiteralSearch 
                                           range:NSMakeRange(0, [numberToDial length])];

        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:numberToDial]];
    }
}
+1  A: 

You can't have a space in the phone number. Strip that out and try again.

marcc
+2  A: 

You need to escape spaces with for example NSString's stringByAddingPercentEscapesUsingEncoding: method.

St3fan
+2  A: 

You will need to sanitize the user input for it to be a valid tel:// URL. Specifically this includes stripping of:

  • Spaces
  • Hashes (#)
  • Asterisks(*)

From iPhone Dev Center:

To prevent users from maliciously redirecting phone calls or changing the behavior of a phone or account, the Phone application supports most, but not all, of the special characters in the tel scheme. Specifically, if a URL contains the * or # characters, the Phone application does not attempt to dial the corresponding phone number.

From URLs for URLs for Telephone Calls RFC:

...spaces MUST NOT be used in phone numbers in URLs as the space character cannot be used in URLs without escaping it.

Igor Zevaka
A: 

St3fan is right, you should use stringByAddingPercentEscapesUsingEncoding before constructing NSURL instance. iPhone OS does other magic automatically for you. If you will not percent escape problem characters then URLWithString: method will return nil.

Roman Busyghin