2010-03-08 76 views
0

我有一個tableView,其中包含帶電話號碼的單元格。該應用程序沒有撥號。請參見下面的代碼爲什麼我的「tel:」鏈接不能正常工作

- (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]]; 
} 
} 

控制檯輸出中: 2010-03-08 01:32:30.830 AIB[1217:207] tel:01 8350098

正如你所看到的,這個數字到控制檯,但沒有得到撥號。奇怪的是,如果我改變的最後一個語句這樣:

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

電話撥打此號碼171,沒有任何問題


,如在以下建議我的特定問題的解決方案,從電話號碼中刪除空格。我做到這一點如下:

- (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]]; 
    } 
} 

回答

5

您需要清理用戶輸入,以使其成爲有效的tel:// URL。具體而言,這包括的剝離:

  • 空間
  • 散列(#
  • 星號(*

iPhone Dev Center

要防止用戶惡意 重定向電話來電或更改 電話或帳戶的行爲, 電話應用程序支持電話方案中的大部分, 但不是全部,特殊字符 。具體而言,如果一個 URL包含*或#字符,則 電話應用程序不會嘗試 撥打相應的電話號碼 。

URLs for URLs for Telephone Calls RFC

...空間不能在電話中使用 號碼網址作爲空格字符 不能在URL中使用而不 逃脫它。

1

在電話號碼中不能有空格。剝離並重試。

2

您需要使用例如NSStringstringByAddingPercentEscapesUsingEncoding:方法轉義空格。

0

st3fan是對的,您應該在構造NSURL實例之前使用stringByAddingPercentEscapesUsingEncoding。 iPhone OS爲你自動執行其他魔法。如果你不會百分之百地逃避問題字符,那麼URLWithString:方法將返回nil。