Swift URLString in unicode

在Swift中字串是支援unicode的,但是转换成NSURL时需要注意的是NSURL中的UrlString必须符合RFC 2396,否则会报错.

The URL string with which to initialize the NSURL object. This URL string must conform to URL format as described in RFC 2396, and must not be nil. This method parses URLString according to RFCs 1738 and 1808.

下面是swift的解决方法.

1
2
3
let str = "myurlString".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())

let url = NSURL(string: str)