Search code examples
iosswiftnsurl

Convert string to NSURL with character '\\' inside


I coding with Swift 2.0.

I got my URL string like this:

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

When I convert it into NSURL, it returns nil.

let OrginUrl = NSURL(string: urlString)

Anyone know how to do this?


Solution

  • There are two issues that need to be addressed:

    In order to include a \ it must be escaped because it is itself the escape character.

    '\' characters are not allowed in URLs so they need to be URL encoded

    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