Swift – WebView demo

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

WebView demo 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.


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() {


let url = NSURL(string: "http://rshankar.com")

let request = NSURLRequest(URL: url)



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.

@IBAction func doRefresh(AnyObject) {




@IBAction func goBack(AnyObject) {




@IBAction func goForward(AnyObject) {




@IBAction func stop(AnyObject) {



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

Download source code from Github

In Category: ios, Programming, Xcode

Ravi Shankar

A polyglot software developer and now exploring Swift and iOS development. If you would like to learn from me then check out services page.

Show 24 Comments
  • ccko August 27, 2014, 1:34 am

    Hello, i follow your steps. But web view does not load the url request.
    Could you please help to identify my code? Thanks

    • rshankar August 27, 2014, 2:23 am

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

      • ccko August 27, 2014, 9:31 am

        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.

        • rshankar August 28, 2014, 6:45 am

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

  • winbert October 9, 2014, 8:57 am

    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!!!

    • rshankar October 9, 2014, 5:28 pm

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

      • winbert October 9, 2014, 6:48 pm

        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!)

  • Isaac Mercer October 11, 2014, 8:39 am

    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?

  • Nick D October 17, 2014, 3:56 am

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

  • CC October 18, 2014, 8:09 pm


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


  • Josh November 24, 2014, 10:06 am

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

  • Balavishnu November 28, 2014, 6:41 pm

    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.

  • swiftguy January 29, 2015, 5:04 am

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

  • Steve May 8, 2015, 11:59 am

    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

    • rshankar May 8, 2015, 12:22 pm

      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

  • Wendel June 22, 2015, 12:21 pm

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

  • Wendel June 23, 2015, 5:12 am

    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() {
    //does not work with http
    //let url = NSURL(string: “http://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!)

    Can you advise a fix. Thanks.

    • rshankar June 23, 2015, 11:18 am

      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.


  • Chad July 13, 2015, 4:05 pm

    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?

  • RaVini August 19, 2015, 1:13 pm

    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!


    • Ravi Shankar August 19, 2015, 1:19 pm

      Thanks for sharing this info.


  • Phong August 25, 2015, 9:24 pm

    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.

  • Diogo November 18, 2015, 2:25 pm

    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.

  • tuhin March 25, 2016, 11:29 am

    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 Comment