在URL查询中使用俄语字符

时间:2017-09-09 12:17:00

标签: ios swift nsurl

我想在网址查询中使用UIWebView的值在UITextField中加载网址:

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(代码= EXC_1386_INVOP,子代码= 0x0)

2 个答案:

答案 0 :(得分:1)

运行时错误的原因是您打开了NSURL的可选实例,实际上是nil

urls nil的原因是searchurl字符串包含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)
    }
}

斯威夫特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)
    }
}

答案 1 :(得分:0)

我非常感谢你

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)
        }
    }
相关问题