I have two ViewControllers. The initial ViewController is where the URL is entered and stored. The viewDidLoad of this initial ViewController is also supposed to start loading the web content for the second ViewController on start of the app.
The secondViewController consists only of a WebView.
When I start the app, func loadWebView in the secondViewController is successfully called. However, once I click the goButton to present the secondViewController. It comes up empty. (Calling func loadWebView locally in the secondViewController viewDidLoad will successfully load the website.)
I think I did something wrong the way I instantiate the secondViewController and the way I call it. I think somehow I am creating two different instances of secondViewController and call the empty one. I'd be happy about any pointers.
EDIT: I want the app to start loading the website as soon as the initial ViewController is opened. Not only when I access the secondViewController.
EDIT2: Could the issue be that the data of the initial call of webView.loadRequest(request) does not get saved to the webView-subview? Calling the webView the second time it comes up blank because no data has been saved. Does anyone know how to save/load data from a loadRequest call?
EDIT3: Forget about EDIT2. Read the comments underneath the correct answer for the solution!
initial ViewController:
var svc: UIViewController = UIViewController()
override func viewDidLoad() {
loadWebView("https://www.google.com")
}
func loadWebView(URLString:String) {
if let theRequestURL = NSURL (string: URLString) {
let theRequest = NSURLRequest (URL: theRequestURL)
let vc: secondViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("secondViewController") as! secondViewController
vc.loadWebView(theRequest)
svc = vc
}
}
@IBAction func goButton(sender: AnyObject) {
self.presentViewController(svc, animated: false, completion: nil)
}
secondViewController:
class secondViewController: UIViewController, UIWebViewDelegate {
@IBOutlet var webView: UIWebView! = UIWebView()
func loadWebView(request : NSURLRequest) {
webView.loadRequest(request)
}
}
I'm not so sure about two instances of secondViewController
, but probably two of webView
...assuming you defined one in your storyboard. Instantiating the IBOutlet
is unusual/wrong.
I suggest turning loadWebView
into something like storeRequestURL
. Save the request to an instance variable and then call loadRequest
in viewWillAppear
(or maybe viewDidLoad
) of secondViewController
.