在 URL 查询中使用俄语字符

Using Russian characters in URL query

我想在 URL 查询中使用 UITextField 的值在 UIWebView 中加载一个 URL:

let texts = SearchBox.text!
let searchurl = "http://sngpoisk.ru/search-location/?search_keywords=\(texts)&search_location=&place_location=&latitude=&longitude="
let urls = NSURL(string:searchurl)
let ret = NSURLRequest(URL:urls!)
Browser!.loadRequest(ret)

但是当texts包含俄文字符时,会出现错误:

EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP , subcode=0x0)

运行时错误的原因是您解包了 NSURL 的一个可选实例,它实际上是 nil.

urls 的原因是 nilsearchurl 字符串包含 invalid 个字符(在 7 位 ASCII 范围之外)。要在 URL 中使用,字符应进行百分比编码。

Swift 2(我猜你用的是那个版本):

let encodedTexts = texts.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
if let encodedTexts = encodedTexts {
    let searchurl = "http://sngpoisk.ru/search-location/?search_keywords=\(encodedTexts)&search_location=&place_location=&latitude=&longitude="
    let urls = NSURL(string:searchurl)
    if let urls = urls {
        let ret = NSURLRequest(URL:urls)
        Browser!.loadRequest(ret)
    }
}

Swift 3:

let encodedTexts = texts.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
if let encodedTexts = encodedTexts {
    let searchurl = "http://sngpoisk.ru/search-location/?search_keywords=\(encodedTexts)&search_location=&place_location=&latitude=&longitude="
    let urls = URL(string:searchurl)
    if let urls = urls {
        let ret = URLRequest(url:urls)
        Browser!.loadRequest(ret)
    }
}

找到了 非常感谢

let texts = Searchd.text!
    let encodedTexts = texts.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())
    if let encodedTexts = encodedTexts {
        let searchurl = "http://sngpoisk.ru/search-location/?search_keywords=\(encodedTexts)&search_location=&place_location=&latitude=&longitude="
        let urls = NSURL(string:searchurl)
        if let urls = urls {
            let ret = NSURLRequest(URL:urls)
            Browser!.loadRequest(ret)
        }
    }