openURL() 中的双标签会使应用程序崩溃

Double hashtag in openURL() crashes the app

我需要从该应用程序进行 phone 调用,目前它正在运行。该号码由两个数字组成:phone 号码和密码,后跟主题标签。 但是有些用户需要在号码的末尾加上双标签,这会导致应用程序在立即调用 URL 时崩溃:

UIApplication.sharedApplication().openURL(NSURL (string: "tel//:1111111,,222##"))

它可以使用单个主题标签,并且可以在设备已经拨号后按键盘上的主题标签。我尝试附加 ASCII table - 十六进制数 23(表示 #) - 它没有帮助。

编辑:

我找到了一些东西 :

let encodedHost = 
numberToDial.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())

它确实像这样交换主题标签:

但是当尝试拨打这个号码 (NSURL) 时,应用程序仍然崩溃。我怎样才能在 URL 的末尾保留双主题标签而不使应用程序崩溃?

我想您的问题的答案在文档中。

To prevent users from maliciously redirecting phone calls or changing the behavior of a phone or account, the Phone app supports most, but not all, of the special characters in the tel scheme. Specifically, if a URL contains the * or # characters, the Phone app does not attempt to dial the corresponding phone number. If your app receives URL strings from the user or an unknown source, you should also make sure that any special characters that might not be appropriate in a URL are escaped properly. For native apps, use the stringByAddingPercentEscapesUsingEncoding: method of NSString to escape characters, which returns a properly escaped version of your original string.

特别是方法 stringByAddingPercentEscapesUsingEncoding 尝试将此方法与您要拨打的字符串一起使用。

问题是 NSURL 认为那不是有效的 URL。这个:

NSURL(string: "tel//:1111111,,222##")

…returns 无。问题不在于逃避;就是 NSURL 显然不接受任何带有两个 # 符号的东西。 (将其粘贴到 playground 中自己进行实验。)它 looks like it ought to, so you might file that as a bug with Apple. However, note this from Apple:

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


我不知道这段代码为什么编译:

UIApplication.sharedApplication().openURL(NSURL(string: "tel//:1111111,,222##"))

NSURL(string:) 是一个可失败的初始化器,这意味着它 returns 是一个可选的,而 openURL() 的参数是非可选的。这会提示您进行这样的检查,以防止崩溃:

if let url = NSURL(string: "tel//:1111111,,222##") {
    UIApplication.sharedApplication().openURL(url)
} else {
    showErrorMessage("Unable to dial this number")
}

您是否可能在 NSURL 构造函数之后有一个 ! 在您为这个问题修剪它时被删除?如果是这样,那将是您崩溃的原因。