I want to call "privacy policy" and "user terms" weblinks on the same WkWebView Controller. I defined two different buttons in the initial view controller and when either of them is pressed I assign the related URL string in the variable. Then I pass it to WkWebView controller via perform segue. Please see both controllers below. My problem is at first run, URL returns nil because when I press the button it jumps to WkWebView Controller and crashes. If I assign a default link at initialization it works as expected. I don't understand why it does not proceed URL assignment line at first run. Any help very much appreciated since I could not find any solution yet. (Apple links are just for example)
Initial controller to assign the URL and perform segues:
class InfoViewController: UIViewController {
var myURL: String?
@IBAction func helpButton(_ sender: UIButton) {
}
@IBAction func privacyPolicyButton(_ sender: UIButton) {
myURL = "https://www.apple.com/legal/intellectual-property/piracy.html"
performSegue(withIdentifier: "GoToWebView", sender: self)
}
@IBAction func termsOfUseButtton(_ sender: UIButton) {
myURL = "https://www.apple.com/legal/internet-services/terms/site.html"
performSegue(withIdentifier: "GoToWebView", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if segue.identifier == "GoToWebView" {
let destinationVC = segue.destination as! WebViewController
destinationVC.url = myURL
}
}
My second controller (WkWebView) to view the weblink as described in Apple document:
class WebViewController: UIViewController, WKUIDelegate {
var webView: WKWebView!
var url: String?
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let myRequest = URLRequest(url: URL(string: url!)!)
webView.load(myRequest)
}
}
I finally found out my mistake in the code. I incorrectly control drag the segue from the action button on the initial controller to the second controller and this caused to run the "prepare for segue" method whenever the button is pressed without processing the next line to assign the URL under IBaction func. I corrected to create the segue from controller to controller and it worked fine.