How to Create a Webview for iOS Applications

Introduction

In this article, we will move forward. Today, we will see how to implement the Web View in iOS App. If you have any knowledge about Android app development, the concept of iOS is the same as Android with a little difference.

Step 1

First, open the the Xcode IDE. Create a project named as “Web View” and click Next. Now, choose the application type as “universal” and language as Swift. Then, create a project. After that, go to the object library, type web view, drag the web view, and drop into ViewController.

ViewController

Step 2

Now, create a new Swift class “Cocoa Touch Class”. Give the class a name as  “WebViewController” and extend with “UIViewController”. Then, bind it with the Web View Controller.

UIViewController

Step 3

Open Xcode Editor in assistant mode and create an outlet of image by pressing Ctrl+Click, and drag into the right side after class declaration.

Xcode

Step 4: In the View Did load method type the following code

Code

  1. let url = NSURL (string"http://www.c-sharpcorner.com/members/khawar-islam2");  
  2. let requestObj = NSURLRequest(URL: url!);  
  3. WebView.loadRequest(requestObj);  
In these three lines of code, first you declare a constant variable named as url. Then, you request the address of the web page which you want to open. After this, we declare another constant for web page request. In the third line, we use outlet of Web View and select a method load request and pass the requestobj variable as a parameter.

Complete Code
  1. import UIKit  
  2. class WebViewController: UIViewController  
  3. {  
  4.     @IBOutlet weak  
  5.     var WebView: UIWebView!override func viewDidLoad() {  
  6.         super.viewDidLoad()  
  7.         let url = NSURL(string"http://www.c-sharpcorner.com/members/khawar-islam2");  
  8.         let requestObj = NSURLRequest(URL: url!);  
  9.         WebView.loadRequest(requestObj);  
  10.     }  
  11.     override func didReceiveMemoryWarning() {  
  12.         super.didReceiveMemoryWarning()  
  13.             // Dispose of any resources that can be recreated.  
  14.     }  
  15. }  
Now, run the app and see if the page opens or not. If the page opens, you need to do nothing. But, if your page does not open, you will move forward and add some permissions.

In some cases, the web page does not open because the operating system does not give permission to your domain. So, we have to give the permission. Move to info.plist file, in the last row type the “App Transport Security Settings”, click the plus button, and add this row.

“Allow Arbitrary Loads”
 
Press Yes in the left side textbox. Now, select “Exception Domains” in which you declare the “Profile” and give the URL of the domain at the right side. We want to access the following URL, so we copy this URL and paste it.
http://www.c-sharpcorner.com.

url

Now, in your app, you can see the result.

result


Similar Articles