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.
Thanks so much for the above tutorial. This page was like a shaft of light in the dark. Many many thanks.
Hi Tom,
I’m glad it is helped.
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?
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
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?
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.
Really thanks, exactly what I was looking for. Works Flawlessly in Xcode 6.3
Hi Mr_Bologna,
I’m glad it is helped.
How can we open a webview with a specific port like as : ex http://www.myip.com:8080 ?
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);
Ok , I have try but Nothing is displayed on my simulator :/
Please, make sure your webpage doesn’t have any errors, while opening mobile browser.
No errors, but maybe there is a problem because I try to open an htacess protected folder ?
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
Is possibble import js files when the UIWebView use LoadHTMLString…. for example how to import jQuery in the content if this is a String???
Thank you. This helped me immensely.
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.
Hi Robert,
no need to create a new viewcontroller, but need to create multiple uiwebview instance.
Do you know how to make this work in Swift 7? I have tried and it doesn’t seem to be working.
X Code 7 is what I meant
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?
yes, you can achieve this using supportedInterfaceOrientation
hi, i have followed the instruction for UIWebView Load URL, when i lunch simulator i have a white page,any help plz ???
Hi, sorry for the delayed response. it works fine just make sure you have followed properly.
My question is related to creating UIWebView programmatically, Can i create the UIWebview from a button click function instead of viewDidLoad?
Yes, you can, Create a new webview object in button click and add it into the current view.
Can i append two more urls in same webview… l
No, Why it is needed?
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.
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.
How do you add a custom header to the request?
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.
add webview.scrollView.scrollEnabled property as true.
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 ?
hi , i don’t know how to fix this error use of unresolved identifier ‘mywebview’ can u pls help
i am using xcode7
i resolved this by deleting the ‘my’ characters. so it just reads ‘webView’
You created an outlet with name “webView” so access it with this name , myWebView is not declared anywhere.
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!!
Apply constrainst on your webview so that it should be below top layout guides.
Thank you but it seems you write this tutorial for Xcode 4. Could you write also for Xcode 7 ?
Hi Mrbengi,
Yes, will consider this and update the tutorial for Xcode 7+ or 8 ASAP.
But how have method calls for a webview
Brilliant tutorial and in detais. Thanks a lot for what you do. Really appreciate.
Cheers,
Pierre
how to stop webview from reloading when the app comes to foreground
call a method while app goes foreground, in that method you can stop the webview.
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