2017-09-09 91 views
0

我想在URL查詢中使用的UITextField值在UIWebView加載網址:網址查詢使用俄文字符

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)

回答

0

運行時錯誤的原因是喲你打開一個NSURL的可選實例,實際上是nil

urls原因是nilsearchurl字符串包含invalid字符(外側的7位ASCII範圍的)。在字符應該百分比編碼的URL中使用。

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