How to load a webview in a SWIFT based ios App - ios

I am relatively very new to swift. Could you please help me how to load a webview in an ios app based on swift. Basically I want to load the contents of an external URL in an ios app.
Can anyone please help?

override func viewDidLoad() {
super.viewDidLoad()
let webV:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
webV.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.google.com")))
webV.delegate = self;
self.view.addSubview(webV)}
and if you want use delegate function
func webView(webView: UIWebView!, didFailLoadWithError error: NSError!) {
print("Webview fail with error \(error)");
}
func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
return true;
}
func webViewDidStartLoad(webView: UIWebView!) {
print("Webview started Loading")
}
func webViewDidFinishLoad(webView: UIWebView!) {
print("Webview did finish load")

Before asking your questions research what you're looking, because this question has been answered on many forums.
In the viewDidLoad() add the following code. Make sure to connect the WebView to the View and to connect the outlet.
let url = NSURL (string: "https://www.google.com");
let requestObj = NSURLRequest(URL: url!);
myWebView.loadRequest(requestObj);
}

Related

UIWebview reload doesn't work

I use UIWebView to load the remote url, the page is blank because the network is unavailable. After network is available ,i reload the UIWebView, but the page is still blank.
How can i solve it?
Try this
func reloadRequest() {
if let url = URL(string: "https://stackoverflow.com") {
let request = URLRequest(url: url);
self.loadRequest(request);
}
}
Load web view with request again, like:
if let url = URL(string: "https://www.google.com") {
let request = URLRequest(url: url)
wvWebView.loadRequest(request)
}
Here is sample code.
#IBOutlet var wvWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
wvWebView.delegate = self
reloadWebview()
}
// call this function to reload web view.
func reloadWebview(){
if let url = URL(string: "https://www.google.com") {
let request = URLRequest(url: url)
wvWebView.loadRequest(request)
}
}
// Webview Delegates
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
print("\n\n**** webView:shouldStartLoadWithRequest: \(request.url) \(navigationType)")
return true
}
func webViewDidStartLoad(_ webView: UIWebView) {
print("webViewDidStartLoad")
}
func webViewDidFinishLoad(_ webView: UIWebView) {
print("webViewDidFinishLoad")
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
print("error description - \(error.localizedDescription)")
}

Swift : Open mailto link in UIWebView

I am developing an application using UIWebView. Inside the web view I have mailto link and I want to open this link in the mail application of iOS.
That is my entire code of the application
override func viewDidLoad() {
//webview.delegate = self;
webview.dataDetectorTypes = UIDataDetectorTypes.all
super.viewDidLoad()
self.webview.delegate = self
let webURL = URL(string: "http://www.collegiodeirettori.net/palio/")
// Do any additional setup after loading the view, typically from a nib.
let urlRequest = URLRequest(url: webURL!)
webview.loadRequest(urlRequest)
webview.scrollView.bounces = false
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
print(request)
let stringaURL = try! String(contentsOf: request.url!, encoding: String.Encoding.ascii)
if navigationType == UIWebViewNavigationType.linkClicked{
if((stringaURL.range(of:"www.collegiodeirettori.net/palio/")) != nil ){
print("ciao")
//print(stringaURL)
}
else{
print(stringaURL)
UIApplication.shared.openURL(request.url!)
//UIApplication.shared.open(URL(string: stringaURL)!)
return false;
}
}
return true;
}
I already made a func that control if a link have to be opened in safari and that works but no for the mailto link..
Any ideas? Thanks!

Add A Callback To A Prebuilt Asynchronous Function Swift iOS

I'm messing around with pdfs at the moment. I'm attempting to load a PDF into the system and write out the same PDF to gain an understandings of the the whole procedure.
The problem I've got it is that I'm having to load the pdf from the web and because the WebViewUI.loadRequest is asynchronous, it isn't completed in time.
override func viewDidLoad() {
super.viewDidLoad()
let filePath = getDocumentsDirectory().stringByAppendingPathComponent("output.pdf")
let url : NSURL! = NSURL(string: "http://www.nhs.uk/NHSEngland/Healthcosts/Documents/2014/HC5(T)%20June%202014.pdf")
loadTemplate(url, completion: {(webView: UIWebView) -> Void in
print("callback started")
let pdf = self.toPDF(webView)
do {
pdf!.writeToFile(filePath, atomically: true)
} catch {
// failed to write file – bad permissions, bad filename, missing permissions, or more likely it can't be converted to the encoding
}
print("callback started")
})
print("Finished viewDidLoad")
}
func loadTemplate(url: NSURL, completion: (webView: UIWebView) -> Void) {
print("Start loadTemplate")
// do some crunching to create the SketchAnimation instance...
let webView = UIWebView(frame: CGRectMake(20, 100, 300, 40))
webView.loadRequest(NSURLRequest(URL: url))
self.view.addSubview(webView)
// invoke the completion callback
completion(webView: webView)
print("finished loadTemplate")
}
How do I add a callback to the loadRequest instead of loadTemplate?
You don't, exactly. You'd set up your view controller to be the web view's delegate and implement the webViewDidFinishLoad method. In that method you'd check to make sure the load that finished is the one you were after, and if so, then you'd invoked the code you want to run when the load is complete.
Here is a basic example of how to set that up:
//
// ViewController.swift
//
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
#IBOutlet var webView: UIWebView!
var url = NSURL(string: "http://google.com")
override func viewDidLoad() {
super.viewDidLoad()
//load initial URL
let req = NSURLRequest(URL : url!)
webView.delegate = self
webView.loadRequest(req)
}
func webViewDidStartLoad(webView : UIWebView) {
print("AA")
}
func webViewDidFinishLoad(webView : UIWebView) {
print("BB")
}
}

Activity indicator not stopping when webview has finished loading

Anyone have an idea why my activity indicator is not stopping when the webview has finished loading? Web view is delegated, UIActivityIndicatorView start animating etc, is in my code... ?
This is the relevant code:
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
#IBOutlet weak var webview: UIWebView!
#IBOutlet weak var activity: UIActivityIndicatorView!
var url = "http://apple.com"
func loadURL () {
let requestURL = NSURL(string: url)
let request = NSURLRequest(URL: requestURL!)
webview.loadRequest(request)
}
override func viewDidLoad() {
super.viewDidLoad()
loadURL()
// Do any additional setup after loading the view, typically from a nib.
webview.delegate = self;
}
func webviewDidStartLoad(_ : UIWebView){
activity.startAnimating()
NSLog("The webview is starting to load")
}
func webviewDidFinishLoad(_ : UIWebView){
activity.stopAnimating()
activity.hidden=true;
NSLog("The webview is done loading")
}
Thanks!
Mind the functions names! It's webView..., camel case :)
Are you getting "The webview is done loading"?. If not, probably the request it's taking a very long time to complete it.
However, you should implement func webView(webView: UIWebView, didFailLoadWithError error: NSError?) to detect if there's any error and stop the activity.
Actually, the correct answer is a probably combination of DAN's and iGongora's, plus a possible third reason.
The immediate problem is that even in a happy path scenario (where the webview finishes successfully) is that it should be the following (pay attention to the case of the function names webViewDidStartLoad and webViewDidFinishLoad
func webViewDidStartLoad(webView: UIWebView) {
activity.startAnimating()
NSLog("The webview is starting to load")
}
func webViewDidFinishLoad(webView: UIWebView) {
activity.stopAnimating()
activity.hidden=true;
NSLog("The webview is done loading")
}
Additionally, if the UIWebView fails, you should also stop the spinner.
func webView(webView: UIWebView!, didFailLoadWithError error: NSError!) {
activity.stopAnimating()
activity.hidden=true;
print("Webview fail with error \(error)");
}
One other possible problem would be if you have not set the delegate properly. You can do it in the viewDidLoad, or in Interface Builder.
override func viewDidLoad() {
super.viewDidLoad()
...
self.webView.delegate = self;
...
}
Run this in main queue so this will stop other wise not the code for this swift 4 and swift 3 is
Dispatchqueue.main.async{
activity.stopAnimating()
}

Creating webViews programmatically in Swift

I want to create something like an image gallery in my ViewController. For this, I'd need multiple webViews, depending on the number of images that I get from a JSON request. How can I insert new webViews if I need to?
As you can see in the above image, I have a scrollView and one UIWebView inside of the ViewController. How would I create a new webView inside of the first(second, third, etc.) if necessary? Is it possible?
you can create the web view programatically as simple as possible use this piece of code
override func viewDidLoad() {
super.viewDidLoad()
let webV:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
webV.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.google.co.in")))
webV.delegate = self;
self.view.addSubview(webV)
}
and if you want use this delegate function
func webView(webView: UIWebView!, didFailLoadWithError error: NSError!) {
    print("Webview fail with error \(error)");
}
func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
    return true;
}
func webViewDidStartLoad(webView: UIWebView!) {
    print("Webview started Loading")
}
func webViewDidFinishLoad(webView: UIWebView!) {
    print("Webview did finish load")
}
For Swift 3:
override func viewDidLoad() {
super.viewDidLoad()
let webV = UIWebView()
webV.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
webV.loadRequest(NSURLRequest(url: NSURL(string: "https://www.apple.com")! as URL) as URLRequest)
webV.delegate = self
self.view.addSubview(webV)
}
Reference: Based on the answer provided by #Deepakraj Murugesan
Although UIWebView is probably not the thing you should use for displaying images, you can create one with just a few lines of code:
let webView = UIWebView(frame: someFrame)
webView.loadRequest(NSURLRequest(URL: someURL!))
view.addSubview(webView)
you can't do that, Originally,webview will take up a lot of memory, if you use some quantity of it, can lead to a bad experience, why do not use ImageView?
For Swift 4:
webView = WKWebView()
webView.navigationDelegate = self
view = webView
let url = URL(string: "https://www.earthhero.org")!
webView.load(URLRequest(url: url))
webView.allowsBackForwardNavigationGestures = true
Plus you need to import WebKit and add WKNavigationDelegate to the Class.

Resources