Marina Marina - 6 months ago 26
iOS Question

Can not create NSURL object because of "|" symbol in url string

I need to create an object of NSURL from url string like this "https://static-maps.yandex.ru/1.x/?l=map&pt=55.1583062965,61.3948104504,pm2rdm|55.1583062962,20.232332,pm2rdm&size=600,300". It contains "|" symbol. The problem is that NSURL constructor always returns nil, because of "|" symbol. How can I create this object?

Answer

I think it is lowercase l, not the pipe | character.

However, you can use stringByAddingPercentEncodingWithAllowedCharacters: with NSCharacterSet.URLQue‌​ryAllowedCharacterSet() to escape invalid characters in the URL:

url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQue‌​ryAllowedCharacterSet())

--

let url = "https://static-maps.yandex.ru/1.x/?l=map&pt=55,1583062965,61,3948104504,pm2rdm&size=600,300"    
let escapedURL = url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQue‌​ryAllowedCharacterSet())
print(NSURL(string: escapedURL))
Comments