Reputation: 55
I want to load a URL in UIWebView
using the value of UITextField
in the URL query:
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)
But when texts
contains Russian characters, an error occurs:
EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP , subcode=0x0)
Upvotes: 1
Views: 2425
Reputation: 2200
The reason of the runtime error is you unwrap an optional instance of the NSURL
, which is actually nil
.
The reason of urls
is nil
is searchurl
string contains invalid characters (outside of the 7-bit ASCII range). To be used in URL that characters should be percent-encoded.
Swift 2 (I guess you are using that version):
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)
}
}
Upvotes: 1
Reputation: 55
I find Thank you very much
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)
}
}
Upvotes: 0