Reputation: 135
I'm developing a tinderlike swipe app for babynames. I've created a method that, when you click a button besides one of your favorite names, it pops up a window (A UIViewController with a WKWebView) that shows a google search with the meaning of this particular name.
The problem is that with some names, the app crashes because the URL returns nil. I don't understand what's happening, because other names are working just fine. I've found out it happens with Scandinavian names like "OddVeig" and "OddLaug" .
Below is my UIViewController class that pops up with the search result (I've put all the initializing code in the layoutSubViews(), because I had some trouble in iOS 12, where the WKWebView wouldn't resize properly if I put it in the viewDidLoad() ) :
import UIKit
import WebKit
class WebViewController: UIViewController, WKNavigationDelegate {
@IBOutlet weak var webContainer: UIView!
var webView : WKWebView!
var query : String?
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidLayoutSubviews() {
webView = WKWebView()
webView.navigationDelegate = self
webContainer.addSubview(webView)
self.view.alpha = 0.9
webView.frame = self.view.frame
webView.layer.position.y += 20
let slideDownImage = UIButton(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 30))
slideDownImage.setImage(UIImage(named: "slideIconWhite"), for: .normal)
slideDownImage.imageView?.contentMode = .scaleAspectFit
if let n = query {
let url = URL(string: "https://www.google.com/search?q=\(n)")! // Causing error: Found nil
webView.load(URLRequest(url: url))
webView.allowsBackForwardNavigationGestures = true
}
webContainer.addSubview(slideDownImage)
slideDownImage.frame = CGRect(x: 0, y: 0, width: self.webView.frame.size.width, height: 20)
slideDownImage.backgroundColor = .gray
slideDownImage.alpha = 0.7
slideDownImage.addTarget(self, action: #selector(slideDown), for: .touchUpInside)
}
@objc func slideDown() {
self.dismiss(animated: true, completion: nil)
}
}
I use a segue in the FavoritesViewController class like this :
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "favoritesToWeb" {
let destination = segue.destination as! WebViewController
destination.query = "\(searchName)+\(NSLocalizedString("meaning", comment: "meaning"))"
}
}
Hopefully someone can tell me what I'm doing wrong. Thanks in advance.
Patrick
Upvotes: 1
Views: 332
Reputation: 877
query
variable need to be percentage encoded, I guess this must be crashing while you have whitespace characters in query string. use addingPercentEncoding
for adding percentage encoding to query string.
Reference to API: https://developer.apple.com/documentation/foundation/nsstring/1411946-addingpercentencoding
Related Question: Swift. URL returning nil
Upvotes: 1