As an iOS developer, you will come across multiple scenarios where you have to display something in web, for that we use WebView.
As per Apple, − It is an object that displays interactive web content, such as for an in-app browser.
So in this post, we will be seeing how to create WebView and load the data in it.
So let’s start
Step 1 − Open Xcode and create a single view application and name it WebViewSample.
Step 2 − Open ViewController.swift file and import the WebKit module. import WebKit
Step 3 − Add a property of WebKit in ViewController.swift.
var webView: WKWebView!
Step 4 − Add WKUIDelegate delegate to ViewController.swift
Step 5 − In ViewController.swift add the below method, add override loadView function.
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}Step 6 − In viewDidLoad create the URL request which you want to load and load the URL
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string:"https://www.apple.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}Step 7 − Run the application,
Complete code
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string:"https://www.apple.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
}