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

时间:2015-10-01 03:46:45

标签: ios swift nsurl

我用 Swift 2.0 进行编码。

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

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

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

let OrginUrl = NSURL(string: urlString)

任何人都知道怎么做?

2 个答案:

答案 0 :(得分: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!)")  
  

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

     

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

答案 1 :(得分:2)

你应该使用unicode而不是反斜杠两次。

  不推荐使用

stringByAddingPercentEscapesUsingEncoding:改为使用stringByAddingPercentEncodingWithAllowedCharacters(_:),它始终使用推荐的UTF-8编码,并对特定的URL组件或子组件进行编码,因为每个URL组件或子组件对于什么都有不同的规则字符有效。

     

文档Reference

以下是示例代码:

let myLink = "http://example.com/api/getfile/?filepath=C:\u{005C}\u{005C}1.txt"
var newLink = ""
if let queryIndex = myLink.characters.indexOf("?"){
    newLink += myLink.substringToIndex(queryIndex.successor())
    if let filePathIndex = myLink.characters.indexOf("=")?.successor() {
        newLink += myLink.substringWithRange(queryIndex.successor()...filePathIndex.predecessor())
        let filePath =  myLink.substringFromIndex(filePathIndex)
        if let pathEscaped = filePath.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPathAllowedCharacterSet()) {
            newLink += pathEscaped
        }
    }
}
if let newURL = NSURL(string: newLink) {
    print(newURL, separator: "", terminator: "")
} else {
    print("invalid")
}

结果你会得到:

  

http://example.com/api/getfile/?filepath=C%3A%5C%5C1.txt