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,
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.
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.
Now, uiwebview added into Main.storyboard ViewController page and looks like below.
Then, click the assistance editor to link the Storyboard ViewController page to viewcontroller.swift by adding the uiwebview reference.
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.
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 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 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 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.
Leave a Reply