我想在网址查询中使用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)
答案 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)
}
}