• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips
You are here: Home / ios / Swift – WebView demo

Swift – WebView demo

November 6, 2019 By Ravi Shankar 24 Comments

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.

Filed Under: ios, Programming, Xcode Tagged With: Swift, WebView, Xcode

Reader Interactions

Comments

  1. ccko says

    August 27, 2014 at 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
    https://github.com/ccko/TheWebView

    Reply
    • rshankar says

      August 27, 2014 at 2:23 am

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

      Reply
      • ccko says

        August 27, 2014 at 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.

        Reply
        • rshankar says

          August 28, 2014 at 6:45 am

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

          Reply
  2. winbert says

    October 9, 2014 at 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!!!

    Reply
    • rshankar says

      October 9, 2014 at 5:28 pm

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

      Reply
      • winbert says

        October 9, 2014 at 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!)

        Reply
  3. Isaac Mercer says

    October 11, 2014 at 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?

    Reply
  4. Nick D says

    October 17, 2014 at 3:56 am

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

    Reply
  5. CC says

    October 18, 2014 at 8:09 pm

    Hello

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

    Thanks!

    Reply
  6. Josh says

    November 24, 2014 at 10:06 am

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

    Reply
  7. Balavishnu says

    November 28, 2014 at 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.
    Thanks.

    Reply
  8. swiftguy says

    January 29, 2015 at 5:04 am

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

    Reply
  9. Steve says

    May 8, 2015 at 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

    Reply
    • rshankar says

      May 8, 2015 at 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 [email protected]

      Reply
  10. Wendel says

    June 22, 2015 at 12:21 pm

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

    Reply
  11. Wendel says

    June 23, 2015 at 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() {
    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.

    Reply
    • rshankar says

      June 23, 2015 at 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.

      Regards,
      Ravi

      Reply
  12. Chad says

    July 13, 2015 at 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?

    Reply
  13. RaVini says

    August 19, 2015 at 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!

    Enjoy,
    RaVini.

    Reply
    • Ravi Shankar says

      August 19, 2015 at 1:19 pm

      Thanks for sharing this info.

      Regards,
      Ravi

      Reply
  14. Phong says

    August 25, 2015 at 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.

    Reply
  15. Diogo says

    November 18, 2015 at 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.

    Reply
  16. tuhin says

    March 25, 2016 at 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?

    Reply

Leave a Reply Cancel 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.

Primary Sidebar

TwitterLinkedin

Recent Posts

  • How to block keywords in Jio broadband
  • How to disable opening an app automatically at login in Mac
  • How to set preferred Wifi network on Mac
  • Attribute Unavailable: Estimated section warning before iOS 11.0
  • How to recover Firefox password from Time Machine backup

Pages

  • About
  • Privacy Policy
  • Terms and Conditions

Copyright 2022 © rshankar.com

Terms and Conditions - Privacy Policy