Source Freeze

  • Home
  • iOS
  • Swift
  • Cross-Platform
  • About
  • Contact
Home » UIWebView example using swift in ios

UIWebView example using swift in ios

August 13, 2022 by Source Freeze 47 Comments

In the Previous ios webview example I have explained about creating ios webview using objective-c, but this tutorial we are going to learn about creating and implementing the uiwebview example using swift programming language.

UIWebView object is used the load and display the web content into your application, safari browser is the primary example for  ios webview. for more reference you can go through apple documentation for uiwebview.


Related: mbprogresshud-example-swift


Open the Xcode, create new project and select the Single View Application template,

uiwebview example single view application

In the next screen, enter the Product Name as “UIWebView Example”, then enter the company identifier details. Select Swift in Language field and Universal in Devices option, Then press next and create the project.

create uiwebview example

Adding UIWebView to View

We can add the UIWebView to View using two methods, first one is adding the uiwebview into storyboard and another one is programatically create uiwebview and adding into the view. first we will add the uiwebview into storyboard viewcontroller.

Open the Main.storyboard file, then at the right bottom of the Xcode you can find ios webview object in the utility area, drag and drop the uiwebview into storyboard viewcontroller page.

select uiwebview from object explorer

Now, uiwebview added into Main.storyboard ViewController page and looks like below.

uiwebview in storyboard

Then, click the assistance editor to link the Storyboard ViewController page to viewcontroller.swift by adding the uiwebview reference.

uiwebview example assistant editor

Then press the control key click the storyboard uiwebview drag into viewcontroller.swift file and place next to viewcontroller class file, as shown in the below.

storyboard uiwebview object reference

UIWebView Load URL

Open the ViewController.swift file and change the below code snippet into the viewDidLoad() function. Here we are generating the NSURLRequest using NSURL object, then passing the request to webview it will load the requested URL into webview.

// UIWebView Load URL 

override func viewDidLoad() { 
super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. 
let url = URL (string: "http://www.sourcefreeze.com"); 
let requestObj = URLRequest(url: url!); 
myWebView.loadRequest(requestObj); 
}

Updated:

if you want to use WKWebView (WebKit)

@IBOutlet weak var webView: WKWebView!

override func viewDidLoad()
{
super.viewDidLoad();
let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.webView.frame.size.height));
self.view.addSubview(webView);
let url = URL(string: "https://sourcefreeze.com");
webView.load(URLRequest(url: url!))
}

  override func loadView() {
      let webConfiguration = WKWebViewConfiguration()
      webView = WKWebView(frame: .zero, configuration: webConfiguration)
      webView.uiDelegate = self
      view = webView
   }

Next, Build and Run the application you will get the output like below.

uiwebview load online url

UIWebView load local html

As like online web page, we can load the local html file into webview. this is the base of hybrid application development using PhoneGap/Cordova. first we have to add the html file using File–>New–>File or Press Command + N, it will open the window like below. then select the Empty file name it as home.html add it into project.

Next, add the below code html code snippet into the home.html file.

<html> 
<head> </head> 
<body> 
<br /> <h2> Welcome SourceFreeze!!!</h2> 
</body> 
</html>

then, go to the ViewController.swift file, modify the viewDidLoad method like below code snippet.

override func viewDidLoad() 
 {         
  super.viewDidLoad()  // Do any additional setup after loading the view, typically from a nib.         
  let localfilePath = NSBundle.mainBundle().URLForResource("home", withExtension: "html");         
  let myRequest = URLRequest(URL: localfilePath!);         
  myWebView.loadRequest(myRequest);     
 }

Next, Build and Run the application you will get the output like below.

uiwebview load local html file

UIWebView LoadHTMLString

Other then direct URL we can load HTML String into UIWebView, we have to pass the htmlstring into loadHTMLString method like the below code snippet, replace this code in the viewDidLoad method.

override func viewDidLoad() 
{ 
super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. 
var htmlString:String! = "<br /><h2>Welcome to SourceFreeze!!!</h2>" 
myWebView.loadHTMLString(htmlString, baseURL: nil) 
}

then build and run the application, you will get the output like below.

uiwebview load local html file

UIWebView Running JavaScript

Like loading the direct html strings into uiwebview, can able to access or run the direct javascript methods into uiwebview using stringByEvaluatingJavaScriptFromString method. the below code will get the html page title using stringByEvaluatingJavaScriptFromString.

let htmlTitle = myWebView.stringByEvaluatingJavaScriptFromString("document.title"); 
println(htmlTitle)

UIWebView LoadData

Instead of web pages, we can also load the document files into iOS WebView  like .pdf, .txt, .doc etc.. loadData method is used to load NSData into webview. Replace the below code snippet into the viewDidLoad.

override func viewDidLoad() 
{ 
super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. 
let localFilePath = NSBundle.mainBundle().pathForResource("home", ofType:"txt"); 
let data = NSFileManager.defaultManager().contentsAtPath(localFilePath!); 
myWebView.loadData(data!, MIMEType: "application/txt", textEncodingName: "UTF-8", baseURL: nil); 
}

UIWebView Properties

UIWebView scalesPageToFit

it is the boolean property used scale the every webpage loaded into uiwebview, if  YES the webpage is allow users to perform zoom in and zoom out operations. if NO user zooming is disabled, by default the value is NO.

UIWebView Detection

Detection property is used to analyze the loaded webpages having any links, email or phone numbers. and events(added to calendar).

UIWebView keyboardDisplayRequiresUserAction

it is boolean variable, this property is set to YES, the user must explicitly tap the input elements in the web view to display the keyboard. When set to be NO, a focus event on an element causes the input view to be displayed and associated with that element automatically and the default value of the property is YES.

UIWebView Navigation operations:

uiwebview allow back, forward and reload to the webpage that already loaded.

goBack() –  is used load the previous web page

goForward() – is used load forward web page.

reload() – is used to reload current web page.

stopLoading() – is used to stop the web content.

mywebView.goBack(); // uiwebview navigate back

mywebView.goForward(); // uiwebview navigate forward

mywebView.reload(); // to refresh the uiwebview

mywebView.stopLoading(); // to stop the loading from uiwebview

canGoBack – it is read only property used to know about is current webpage is can able to go back. for example if we are loaded webpage into first time we are  not able to go back.

canGoForward – it is read only property used to know about is current webpage is can able to go forward.

loading – it is the read only property, used to check the webview is loading or not, If YES the webview is loading otherwise NO.

Create uiwebview programmatically

Instead  of create the uiweview using storyboard, we can create the uiwebview programmatically using the below code. Here we are generating the NSURLRequest using NSURL object, then passing the request to webview it will load the requested URL into webview next add the uiwebview into viewcontroller view.

override func viewDidLoad() 
{                
  super.viewDidLoad()           
  let myWebView:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))         
  myWebView.loadRequest(URLRequest(URL: URL(string: "https://sourcefreeze.com")!))         
  self.view.addSubview(myWebView)     
}

then build and run the project will get the output like below.

uiwebview load online url

Filed Under: ios-tutorial, swift, uiwebview, WKWebView Tagged With: iOS, swift, uiwebview

Comments

  1. Tom says

    December 29, 2014 at 11:19 pm

    Thanks so much for the above tutorial. This page was like a shaft of light in the dark. Many many thanks.

    Reply
  2. sourcefreeze says

    January 2, 2015 at 7:20 am

    Hi Tom,

    I’m glad it is helped.

    Reply
  3. Tom says

    February 27, 2015 at 4:16 pm

    One question. I have the web view working in portrait with no problem but the moment I rotate to landscape I loose the right 1/4(more or less) of the screen. How do I get the view to resize?

    Reply
    • sourcefreeze says

      March 1, 2015 at 12:48 pm

      Hi Tom,

      For Supporting landscape and portrait mode, you must need to implement the auto layout feature. More information please refer the below apple documentation link.

      https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/Introduction/Introduction.html

      Thanks,
      Bharathi D

      Reply
  4. zfc says

    April 19, 2015 at 1:40 am

    I have more than one html files which link to each other and their image resources which put under a folder. What should I do to make it work?

    Reply
    • sourcefreeze says

      April 20, 2015 at 10:58 am

      Hi zfc,

      Include www folder with folder reference, then set index page full path for e.g www/index.html, it will automatically pick resource reference because it is referred in your html page.

      Reply
  5. Mr_Bologna says

    April 20, 2015 at 10:37 am

    Really thanks, exactly what I was looking for. Works Flawlessly in Xcode 6.3

    Reply
    • sourcefreeze says

      April 20, 2015 at 10:59 am

      Hi Mr_Bologna,

      I’m glad it is helped.

      Reply
  6. ewan says

    April 27, 2015 at 1:06 pm

    How can we open a webview with a specific port like as : ex http://www.myip.com:8080 ?

    Reply
    • sourcefreeze says

      April 27, 2015 at 4:02 pm

      Hi ewan,

      you can use the same code for loading online URL by just adding the port number in the end of URL.. like below.

      let url = NSURL (string: “http://www.myip.com:8080”);

      let requestObj = NSURLRequest(URL: url!);

      myWebView.loadRequest(requestObj);

      Reply
      • ewan says

        April 27, 2015 at 4:15 pm

        Ok , I have try but Nothing is displayed on my simulator :/

        Reply
        • sourcefreeze says

          April 27, 2015 at 4:43 pm

          Please, make sure your webpage doesn’t have any errors, while opening mobile browser.

          Reply
          • ewan says

            April 28, 2015 at 2:22 pm

            No errors, but maybe there is a problem because I try to open an htacess protected folder ?

          • dark cafe says

            November 29, 2016 at 12:43 am

            Had the same problem. iOS security “may” be blocking access, check your console. Solution in this article solved it for me: http://stackoverflow.com/questions/31254725/transport-security-has-blocked-a-cleartext-http

  7. Andres Chable says

    May 7, 2015 at 10:07 pm

    Is possibble import js files when the UIWebView use LoadHTMLString…. for example how to import jQuery in the content if this is a String???

    Reply
  8. Joseph Bentivegna says

    July 23, 2015 at 6:03 pm

    Thank you. This helped me immensely.

    Reply
  9. Robert Wing says

    August 11, 2015 at 2:10 pm

    This is a great tutorial, one question if i have multipule links to multipul webpages how can this be done? do i have to create a new viewcontroller for each.

    Reply
    • sourcefreeze says

      August 15, 2015 at 3:53 am

      Hi Robert,

      no need to create a new viewcontroller, but need to create multiple uiwebview instance.

      Reply
  10. Grayson faircloth says

    September 18, 2015 at 11:49 pm

    Do you know how to make this work in Swift 7? I have tried and it doesn’t seem to be working.

    Reply
    • Grayson faircloth says

      September 18, 2015 at 11:50 pm

      X Code 7 is what I meant

      Reply
  11. Supremvanam says

    September 20, 2015 at 3:58 am

    I want my UIWebView to be locked in portrait mode until the progress view is finished loading,then allow it to support all orientations.. is this possible?

    Reply
    • sourcefreeze says

      September 20, 2015 at 4:23 am

      yes, you can achieve this using supportedInterfaceOrientation

      Reply
  12. ely says

    September 27, 2015 at 10:35 am

    hi, i have followed the instruction for UIWebView Load URL, when i lunch simulator i have a white page,any help plz ???

    Reply
    • sourcefreeze says

      October 17, 2015 at 12:36 pm

      Hi, sorry for the delayed response. it works fine just make sure you have followed properly.

      Reply
  13. v1111 says

    October 16, 2015 at 2:07 pm

    My question is related to creating UIWebView programmatically, Can i create the UIWebview from a button click function instead of viewDidLoad?

    Reply
    • sourcefreeze says

      October 17, 2015 at 12:34 pm

      Yes, you can, Create a new webview object in button click and add it into the current view.

      Reply
  14. Raja S says

    December 15, 2015 at 6:15 pm

    Can i append two more urls in same webview… l

    Reply
    • sourcefreeze says

      August 14, 2016 at 5:43 pm

      No, Why it is needed?

      Reply
  15. Burak Demirpolat says

    January 31, 2016 at 10:49 pm

    Hi. I have a problem. I am doing every steps until to first ” Build and Run”

    override func viewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.

    let url = NSURL (string: “http://www.sourcefreeze.com”);

    let requestObj = NSURLRequest(URL: url!);

    myWebView.loadRequest(requestObj);

    its okey until these step

    but when i am click to “build and run”
    i have an error. ” App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app’s Info.plist file.”

    what is it mean? what am i doing theese error. Code is true, i am doing copy and paste from here, i have not any code error or red alert.

    Reply
    • john says

      February 9, 2016 at 3:09 pm

      Hey, i had this problem too. Here is how to fix it. First click on your info.plist file. Then click on the + sign next to Information Property List. Now in the box type “NSAppTransportSecurity” and set the type to Dictionary. However, it should do this for you, also it should change “NSAppTransportSecurity” to App transport security settings.. for you. Anyway, once youve done that, you’re going to click on the little arrow next to the “NSAppTransportSecurity” that you just added so that it is pointing downwards. Then click on the + again and add this “NSAllowsArbitraryLoads” and set type to boolean. However, like before it should do this automatically and change NSAllowsArbitraryLoads to Allow Arbirtary loads for you. BUT in the value section for NSAllowsArbitraryLoads type in YES. It will be NO by default, so change it to YES. Here is a screenshot of what is should look like: http://snag.gy/xPYGM.jpg . And here is the stackoverflow question that i learned this from : http://stackoverflow.com/questions/31254725/transport-security-has-blocked-a-cleartext-http

      You’re welcome.

      Reply
  16. Nikolas Manuelides says

    February 19, 2016 at 2:26 pm

    How do you add a custom header to the request?

    Reply
  17. Tuhin says

    March 25, 2016 at 10:36 am

    Hi dear, its a very helpful tutorial. But in my xcode i cannot scroll down to the bottom of the page. Only the upper portion is loading. What can i do? Please help.

    Reply
    • sourcefreeze says

      August 14, 2016 at 5:42 pm

      add webview.scrollView.scrollEnabled property as true.

      Reply
  18. PAWAN SHAHANI says

    April 6, 2016 at 4:05 am

    Could you please guide me :

    What to do if my URL is a private Server & its certificate is expired.
    i.e. Server URL = https://203.xxx.xxx.xxx
    & when i hit this URL from Safari it says : “Safari can’t verify the identity of the Server…..”

    I want to the load the same URL in UIWebview & bypass this error. How can i do this ?

    Reply
  19. rafael says

    May 6, 2016 at 10:21 pm

    hi , i don’t know how to fix this error use of unresolved identifier ‘mywebview’ can u pls help
    i am using xcode7

    Reply
    • Jono says

      May 12, 2016 at 1:02 am

      i resolved this by deleting the ‘my’ characters. so it just reads ‘webView’

      Reply
      • Adnan says

        May 23, 2016 at 4:56 am

        You created an outlet with name “webView” so access it with this name , myWebView is not declared anywhere.

        Reply
  20. Jess Fryer says

    May 22, 2016 at 2:27 pm

    Hi, I don’t get any errors with this, and the app is running, but my app is just to the right of the screen. Do you know why this could be? Thank you!!

    Reply
    • Adnan says

      May 23, 2016 at 4:55 am

      Apply constrainst on your webview so that it should be below top layout guides.

      Reply
  21. mrbengi says

    July 13, 2016 at 10:09 am

    Thank you but it seems you write this tutorial for Xcode 4. Could you write also for Xcode 7 ?

    Reply
    • sourcefreeze says

      August 14, 2016 at 5:38 pm

      Hi Mrbengi,

      Yes, will consider this and update the tutorial for Xcode 7+ or 8 ASAP.

      Reply
  22. Asim Khan says

    July 19, 2016 at 3:11 am

    But how have method calls for a webview

    Reply
  23. Pierre-Henry Soria says

    August 3, 2016 at 9:33 pm

    Brilliant tutorial and in detais. Thanks a lot for what you do. Really appreciate.

    Cheers,
    Pierre

    Reply
  24. Prashanth Kp says

    August 10, 2016 at 10:34 am

    how to stop webview from reloading when the app comes to foreground

    Reply
    • sourcefreeze says

      August 14, 2016 at 5:37 pm

      call a method while app goes foreground, in that method you can stop the webview.

      Reply
  25. Patrick says

    September 29, 2016 at 7:28 pm

    Hello, how can i save the website in the device cache so that i can watch the website content offline if no internet connection available?
    thanks Patrick

    Reply

Trackbacks

  1. UIActivityindicatorview example in ios using swift - Source Freeze says:
    February 26, 2016 at 7:27 am

    […] Related: Webview Example in swift  […]

    Reply

Leave a Reply Cancel reply

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

Recent Posts

  • Parse Float with 2 decimals in javascript
  • Best Next JS courses to learn Next JS in 2023
  • How to redirect to another page in next js
  • How to get the query parameters from URL in Next JS?
  • iOS DatePicker tutorial (UIDatePicker) using Swift
  • UIAlertController iOS 8 using Swift

Recent Posts

  • Parse Float with 2 decimals in javascript
  • Best Next JS courses to learn Next JS in 2023
  • How to redirect to another page in next js
  • How to get the query parameters from URL in Next JS?
  • iOS DatePicker tutorial (UIDatePicker) using Swift
  • UIAlertController iOS 8 using Swift

Recent Comments

  • zulfi on iOS UIPickerView Example using Swift
  • Muhsin on Cordova InAppBrowser Plugin Example using ionic framework
  • SourceFreeze on Cordova InAppBrowser Plugin Example using ionic framework
  • Muhsin on Cordova InAppBrowser Plugin Example using ionic framework
  • SourceFreeze on Cordova InAppBrowser Plugin Example using ionic framework
  • Muhsin on Cordova InAppBrowser Plugin Example using ionic framework

Tags

cross-platform ionic iOS javascript mobile application development nextjs objective-c swift uiwebview Visual Studio plugin

Copyright © 2023 Source Freeze