blvckcode blvckcode - 1 year ago 204
Swift Question

Reload UIWebView with UIButton when both are implemented programmatically (Swift)

I have a UIWebView that loads a embed SoundCloud track. I copied the code from the website, created a html file, and included it inside of the Xcode project. It loads perfectly fine; however, I want the user to be able to reload the WebView since the UIWebView is very small and it does not have any navigation buttons. It simply displays SoundCloud embed widget.

Is there a way to achieve this without using the Interface Builder? The app crashes when the button is tapped.

I have implemented the UIWebView and UIButton onto the screen programmatically because the size and coordinates of each will be different depending on the size of the iPhone screen.

The UIWebView is set to nil before the viewDidLoad function so it can be accessed in other functions (like the reload function).

class SecondViewController: UIViewController, UIWebViewDelegate {

let WebView: UIWebView! = nil
override func viewDidLoad() {

let WebViewDetails = getCoordAndSize("WEBV") // stores 4 values into one variable. its a tuple
let WebView = UIWebView(frame: CGRectMake(WebViewDetails.0, WebViewDetails.1, WebViewDetails.2, WebViewDetails.3))

//load local html file
let localfilePath = NSBundle.mainBundle().URLForResource("sctrack", withExtension: "html")
let myRequest = NSURLRequest(URL: localfilePath!)
WebView.delegate = self

let refreshButton = UIButton()
refreshButton.setTitle("Refresh", forState: .Normal)
refreshButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
refreshButton.backgroundColor = UIColor.clearColor()
refreshButton.layer.cornerRadius = 5
refreshButton.layer.borderWidth = 1
refreshButton.layer.borderColor = UIColor.whiteColor().CGColor
refreshButton.frame = CGRectMake((self.view.frame.size.width - 240) / 2, (imageViewDetails.2 - 40),240,40)

//(LOOK HERE) BUTTON ACTION . What I want it to do is to reload html file when user taps on it
refreshButton.addTarget(self, action: #selector(reload), forControlEvents: .TouchUpInside)

Below is the function for the refreshButton. When the user taps the button, it calls the reload function. I want it to reload the local file. I added the comment saying "ERROR HERE" to

func reload(sender: UIButton!) {

let alertView = UIAlertController(title: "Message", message: "Track refreshed! Enjoy

Answer Source

You are not initializing WebView which you have declared at class level. And again in viewDidLoad you are creating another variable with same name

      let WebView = UIWebView(frame: CGRectMake(WebViewDetails.0, WebViewDetails.1, WebViewDetails.2, WebViewDetails.3))

So your WebView used in reload method never initialized and hence the error/crash.

Remove let keyword in viewDidLoad for WebView. Everything will work fine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download