Swift – WebView demo

Updated for Swift 5

In this short tutorial, we will see an example in Swift programming language using UIWebView. The WebView will load a webpage and provide option to refresh, stop, go back and go forward. This tutorial should give a brief overview on how to declare IBAction, IBOutlets and use Objective-C classes (NSURL and NSURLRequest) in Swift


Interface Design

Step 1: Create a Single View Application Project and make sure to select the programming language as Swift

Choose Swift Language in Xcode

Step 2: Select Main.Storyboard under Project navigator. then drag and drop WebView and Toolbar from Object Library to the View Controller.

Step 3: Now place four bar button items on Toolbar to provide stop, refresh, go back and go forward functionality. You can also use flexible and fixed separators for aligning the bar button items.

Use Suggested Constraints in Xcode 6

Step 4: Make sure to use the SuggestedConstraints for WebView and Toolbar. You can do this by selecting the controls and using the Reset to Suggested Constraints available as part of Resolve Auto Layout option. This would ensure that the controls gets adjusted automatically depending upon the device’s screen width and height.

Reset to Suggested Constraints

Updated – 28/08/2014

Since some users are facing problems with Reset to Suggested Constraints in Xcode 6 Beta 6, you can use Pin option to define the four constraints using the default values. Then click Add 4 Constraints available at the bottom of the screen.

201408281213.jpg

Write Code

Step 5: Navigate to ViewController.swift file on the Project Navigator. Add the following line after class ViewController: UIViewController which defines the IBOutlet element for WebView.

@IBOutlet var webView: UIWebView!

Then connect this IBOutlet element to the WebView on InterfaceBuilder.

Step 6: In the viewDidLoad function, create URL and NSURLRequest for the webpage and associate this with the WebView by calling loadRequest method.

override func viewDidLoad() 
{   
  super.viewDidLoad() 
  let url = NSURL(string: "https://rshankar.com")
  let request = NSURLRequest(url: url! as URL)       
  webView.delegate = self
  activityIndicator.hidesWhenStopped = true
  activityIndicator.startAnimating()
  webView.loadRequest(request as URLRequest) 
}

Step 7: Now add the corresponding IBAction methods for the four buttons stop, refresh, go back and go forward. And connect these IBActions to the buttons on Interface builder.

func webViewDidFinishLoad(_ webView: UIWebView) 
{ 
      activityIndicator.stopAnimating()   
}                                                                                           

@IBAction func doRefresh(_: AnyObject) {                                                              
  webView.reload()
}

@IBAction func goBack(_: AnyObject) 
{   
   webView.goBack()    
}

@IBAction func goForward(_: AnyObject) {
  webView.goForward()
}

@IBAction func stop(_: AnyObject) 
{
   webView.stopLoading()
}

Step 8: Compile and run the project by selecting a suitable simulator.

Download the souce code from GitHub.


Comments

24 responses to “Swift – WebView demo”

  1. Hello, i follow your steps. But web view does not load the url request.
    Could you please help to identify my code? Thanks
    https://github.com/ccko/TheWebView

    1. Can you try clearing the constraints, I did that with your sample code and it looks ok to me.

      1. I clear the constraints and webview can load the request.
        (but the web view width is not right in both simulator and device)
        Then I use reset to suggested constraints.
        the webview not load the request.
        I need to use that to make the layout look fine.

        Please tell me how to adjust the constraints.

        Thank you very much.

        1. I have updated the post to use pin option to define the constraint. Can you please try.

  2. Thank you for the demo!
    But I get an error in the line “let request = NSURLRequest(URL: url)”:
    >Value of optional type ‘NSURL?’ not unwrapped; did you mean to use ‘!’ or ‘?’ ?<
    Did you have an idea to fix the problem?
    Thank you!!!

    1. Have you tried the attached code from GitHub? Let me know if you are still facing the problem

      1. Yes, I have the original from GitHub! I have accepted the offer of xcode and append an exclamation mark to the variable “url”. I had tried that before, but now he has accepted it and it runs …
        The code now: let request = NSURLRequest(URL: url!)

  3. Isaac Mercer Avatar
    Isaac Mercer

    Hi, When I try to include multiple web views in the app using the code above with the identifiers changed to reflect the different webviews it errors out saying “fatal error: unexpectedly found nil while unwrapping an Optional value”. Can you have a look at my code at https://github.com/imercer/nos-app and let me know if I have done anything wrong?

  4. You need a screen shot for ‘Object Library’ in point 2. Been trying to find it for 20 minutes – nothing.

  5. Hello

    I just wondered how this code could be applied to a Mac app made in Swift?

    Thanks!

  6. Would it be possible to open links in a second webView?

  7. Nice tutorial. I have 2 requests. Can you please tell me how to do it?
    1. I would like to have a loader, can you tell me which event you fire after website has finished loading? So that I can stop the loader
    2. Can I set a local html file to web view? If yes then please tell how and share the code.
    Thanks.

  8. great tutorial. simple and direct. Thanks for sharing it.

  9. Assume someone knows nothing, and this is their 1st time in xcode..

    “Then connect this IBOutlet element to the WebView on InterfaceBuilder.”

    What and where is the InterfaceBuilder?
    How do I “Connect the webview to the IBOutlet” If I do find the InterfaceBuilder

    1. rshankar Avatar
      rshankar

      Interface builder in Xcode is the screen where you design your UI. Selecting Main.storyboard file in navigator (left hand side), should display the interface builder.

      If this doesn’t help, we can have a demo in Google Hangout or Skype – Send me an email for a demo ravi@rshankar.com

  10. When I run the code, the iOS simulator is blank (white screen).
    Do I need a physical device. Thanks.

  11. I am able to view websites with https… prefix but, am unable to view web sites with iOS simulator using http….
    Sample code attached.
    override func viewDidLoad() {
    super.viewDidLoad()
    //does not work with http
    //let url = NSURL(string: “https://rshankar.com”)
    //let url = NSURL(string: “http://google.com”)

    //works ok with https
    let url = NSURL(string: “https://en.wikipedia.org/wiki/HTTPS”)
    //let url = NSURL(string: “https://google.com”)

    let request = NSURLRequest(URL: url!)
    webView.loadRequest(request)
    }

    Can you advise a fix. Thanks.

    1. Not sure about this problem. I have tried this and look fine in my simulator.
      Now I have added activity Indicator view as well, can you please download the latest source and try again.

      Regards,
      Ravi

  12. I am having issues with popups on certain websites. I need them enabled in order to view certain aspects of the website…IE someone clicks on a button and a popup is loaded which is a connected website popup asking for more information and digital signatures. The popups fail to load. Is there something specific that is needing to be added?

  13. You have to add some in the Info.plist :

    NSAppTransportSecurity as an Dictionary and than create an Item in the new Dictionary, named NSAllowsArbitraryLoads and type them as an BOOL and say YES.

    That’s all. Now you can get HTTP Requests without HTTPS!

    Enjoy,
    RaVini.

    1. Thanks for sharing this info.

      Regards,
      Ravi

  14. Wonderful tutorial! I followed your steps above and got it working perfectly. Thank you very much! If you have time, would you please consider creating another “swift” demo for getting a XML data from a Web Service, then parse the result and display the result in a simple TableView. So far, most examples on the Web was about JSON. Sadly, the Web Service that I’m trying to interface with would return data only in XML format.

  15. To make this work, i had to edit my Info.plist like this:
    – App Transport Security Settings
    — Allow Arbitrary Loads: YES

    Maybe because i am testing in a real device.

  16. Hi dear it’s a very helpful post to me. Every thing works fine. But in my xcode simulator i cannot load the whole webpage top to bottom by scrolling. It can scroll only the upper portion. What should i do?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.