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() {
super.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.loadRequest(myRequest)
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)
self.view.addSubview(refreshButton)
}
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!) {
//ERROR HERE
WebView.reload()
let alertView = UIAlertController(title: "Message", message: "Track refreshed! Enjoy 🤘🏾✨", preferredStyle: .Alert)
// Initialize Actions
let okAction = UIAlertAction(title: "Ok", style: .Default) { (action) -> Void in
}
alertView.addAction(okAction)
self.presentViewController(alertView, animated: true, completion: nil)
}
}
I've tried to include the html request inside of reload function and used WebView.loadRequest(myRequest) instead of WebView.reload, but the app still crashes.