将字符串转换为NSURL,其中包含字符'\\'

And*_*ham 2 nsurl ios swift

我用Swift 2.0编写代码.

我得到了这样的URL字符串:

let urlString = "http://example.com/api/getfile/?filepath=C:\\1.txt"
Run Code Online (Sandbox Code Playgroud)

当我将其转换为NSURL时,它返回nil.

let OrginUrl = NSURL(string: urlString)
Run Code Online (Sandbox Code Playgroud)

有人知道怎么做吗?

zap*_*aph 5

有两个问题需要解决:

为了包含\它必须进行转义,因为它本身就是转义字符.

URL中不允许使用'\'字符,因此需要对其进行URL编码

let urlString = "http://example.com/api/getfile/?filepath=C:\\\\1.txt"  
print("urlString: \(urlString)")  

var escapedString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())  
print("escapedString!: \(escapedString!)")  

let orginUrl = NSURL(string: escapedString!)  
print("orginUrl: \(orginUrl!)")  
Run Code Online (Sandbox Code Playgroud)

urlString:http://example.com/api/getfile/? filepath = C:\\\ ttxt

escapedString!:
http%3A%2F%2Fexample.com%2Fapi%2Fgetfile%2F%3Ffilepath = C%3A%5C%5C1.txt

orginUrl:
http%3A%2F%2Fexample.com%2Fapi%2Fgetfile%2F%3Ffilepath = C%3A%5C%5C1.txt