字符串中的奇怪不可见字符导致NSURL失败 [英] Strange Invisible Character in String causing NSURL to fail

查看:96
本文介绍了字符串中的奇怪不可见字符导致NSURL失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个字符串到数字的问题,这需要几天的时间才能解决。因此,这一切都始于我的应用程序,其中涉及从通讯录中获取电话号码并拨打电话。一切正常,直到我注意到某些电话号码导致我的程序崩溃。

I am having a String to Number problem that is taking me days to resolve. So it all started out in my app that involves taking a phone number from the addressbook and making a call. Everything was working fine until I noticed some phone numbers were causing my program to crash.

一段时间后,我终于发现他们的电话号码崩溃了。里面有一个空格,这最终是有道理的,因为即使这是一个电话号码,我仍在使用NSURL呼叫 tel://(555)555 5555,并且两者之间有空格会使URL无效,这导致我的程序

After some time, I finally figured that they were crashing for the phone numbers that had a space in it, which finally made sense because even though it is a phone number I am using NSURL to call "tel://(555) 555 5555" and having a space between it will make the URL invalid which was causing my program to crash.

现在,我很高兴找出第二个问题,并决定进行简单的字符替换,将所有空格替换为-。这适用于我测试过的测试字符串,一切看起来都不错。我决定将其备份到我的代码中,然后我的程序仍然崩溃。

Now I was happy I figured out the second problem and decided to do a simple character replacement to replace all whitespace with "-". This worked for the test string I tested it on and everything looked good. I decided to hook this back up to my code and then my program is still crashing.

然后我做了一些调试,发现即使我的测试用例可行,电话号码我是从iOS通讯录中拉取的,没有替换空白。看来,用来分隔电话号码的任何字符都不是空格,或者至少不是空格,我可以这样简单地键入->

I then did some debugging and noticed even though my test case worked, the phone numbers I am pulling from the iOS address book were not having the whitespace replaced. It seems that whatever character is being used to space out the phone digits is not a whitespace or at least it is not a whitespace that I can simply type like this -> " "

任何想法如何解决这个问题? (1)确切知道这个不可见的字符是什么并替换掉它,或者(2)是否有一种方法可以将电话号码提取为所有数字而不是多余的字符 +(。)-或此处的任何选项?

Any idea how to resolve this? Either (1) to know what exactly this invisible character is and replace it or (2) is there a way to just extract a phone number as all numbers instead of the extra chars "+(.)- " or any option here?

推荐答案

您必须使用.stringByAddingPercentEscapesUsingEncoding来转换特殊字符。

You have to use .stringByAddingPercentEscapesUsingEncoding to convert special characters.

let myLink = "http://google.com"

let myUrl = NSURL(string: myLink.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)!

这篇关于字符串中的奇怪不可见字符导致NSURL失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆