Connect a UIProgressView to a UIWebView - Swift/Objective-c - ios

I've got a UIWebView on my storyboard, loading a page from my blog.
I'd like to put also a UIProgressView there... but I don't really know how to connect that to my Web View.
Can you help me?
PS: My main project is in Swift, but if you have a solution working with Objective-C, post it anyway and I'll try to convert it :)
Thanks

Thy this out in swift 3
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "https://topdigital.agency")
let request = NSURLRequest(url: url as! URL)
webView.loadRequest(request as URLRequest)
webView.delegate=self
}
func webViewDidStartLoad(_ webView: UIWebView) {
self.progressView.setProgress(0.1, animated: false)
}
func webViewDidFinishLoad(_ webView: UIWebView) {
self.progressView.setProgress(1.0, animated: true)
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
self.progressView.setProgress(1.0, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

One way is to use the UIWebViewDelegate. Just set the webview.delegate = self. The UIActivityIndicator will be in the right corner of the UINavigationBar. If you have no navigation bar, you can just set a position for the UIActivityIndicator and call activityIndicator.stopAnimationg() to stop the animation.
func webViewDidStartLoad(webView: UIWebView) { //start
var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .White)
var activityBarButtonItem = UIBarButtonItem(customView: activityIndicator)
navigationItem.rightBarButtonItem = activityBarButtonItem
activityIndicator.startAnimating()
}
func webViewDidFinishLoad(webView: UIWebView) { //stop
navigationItem.rightBarButtonItem = nil
}

Related

ViewController is loading always the same link

I am new to swift and ios.The View Controller launch always the same link and do do not show the grid menu with buttons that is in second scene.What i am doing wrong here?
I have in main.storyboard three scene.
In the first scene is navigation.The second scene is a grid menu with buttons that depending on the button click will open a link in webview located in the 3rd scene.The third scene includes a view that should open a specific link depending on the click button in step 2
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView : WKWebView!
var webi:String = "https://www.google.al"
override func viewDidLoad() {
print("‼️OMG:viewDidLoad", webi)
super.viewDidLoad()
let url = URL(string: webi)!
webView.load(URLRequest(url: url))
let refresh = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(webView.reload))
toolbarItems = [refresh]
navigationController?.isToolbarHidden = false
}
override func loadView() {
webView = WKWebView()
webView.navigationDelegate = self
view = webView
}
#IBAction func Menu1(_ sender: Any) {
print("‼️OMG:viewDidLoad with menu1")
webi = "https://www.menu1.com"
}
#IBAction func Menu2(_ sender: Any) {
print("‼️OMG:viewDidLoad with menu1")
webi = "https://www.menu2.com"
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
title = webView.title
}
}
Your problem is that you change the urlStr webi without reloading the webview again
func refresh() {
let url = URL(string: webi)!
webView.load(URLRequest(url: url))
}
#IBAction func Menu1(_ sender: Any) {
print("‼️OMG:viewDidLoad with menu1")
webi = "https://www.menu1.com"
self.refresh()
}
#IBAction func menu2(_ sender: Any) {
print("‼️OMG:viewDidLoad with menu1") // other link
webi = "https://www.menu1.com"
self.refresh()
}
///
Navigation->buttons Menu VC -> webViewVC
while your are in buttons menu
let vc = ViewController()
vc.webi = "" // set link according to the clicked button
self.navigationController?.pushViewController(vc,animated:true)
Look to this Demo

Swift onfinish load event of a UIWebView

I'm loading a pdf in WebView from my server with this code :
webView = UIWebView(frame: CGRectMake(0, y, screenSize.width, screenSize.height-y))
let url : NSURL! = NSURL(string: urlFile)
webView?.loadRequest(NSURLRequest(URL: url))
webView?.opaque = false;
webView?.backgroundColor = UIColor.clearColor()
webView?.scalesPageToFit = true;
self.view.addSubview(webView!)
This code works but how can i receive an event "onPageLoad"?
sorry for bad english, i'm italian(:
You need to implement UIWebViewDelegate like this and use webViewDidFinishLoad to know the page is loaded successfully, for that set the webView delegate with your viewController like this, and implement the webViewDidFinishLoad method inside your viewController like below example.
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
webView = UIWebView(frame: CGRectMake(0, y, screenSize.width, screenSize.height-y))
let url : NSURL! = NSURL(string: urlFile)
webView?.loadRequest(NSURLRequest(URL: url))
webView?.opaque = false;
webView?.backgroundColor = UIColor.clearColor()
webView?.scalesPageToFit = true;
webView?.delegate = self// Add this line to set the delegate of webView
self.view.addSubview(webView!)
}
func webViewDidFinishLoad(webView : UIWebView) {
//Page is loaded do what you want
}
}
In case someone is looking solution for WKWebView, implement WKNavigationDelegate:
add webView.navigationDelegate = self
and then use:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
}
After webView?.loadRequest(NSURLRequest(URL: url)) this, set the webView to self (Write the below line).
webView.delegate = self
Implement the webview delegate methods.
You will get callback in func webViewDidFinishLoad(_ webView: UIWebView) on completing the page load.
func webViewDidFinishLoad(webView: UIWebView) {
//handle the callback here when page load completes
}
Just use effective with ;
func webViewDidFinishLoad(webView : UIWebView) {
// Here your loaded codes.
}

Swift WKWebView and Javascript Interaction

I've been having trouble getting a WKWebView in Swift to trigger some javascript in the loaded web page. Im just trying to use javascript to change a background color on the website if the user swipes left, swipes right, or clicks a button. Any help is greatly appreciated.
import UIKit
import WebKit
class myViewController: UIViewController, WKNavigationDelegate {
#IBOutlet var container: UIView!
var webView: WKWebView?
override func viewDidLoad() {
super.viewDidLoad()
self.webView = WKWebView()
container.addSubview(webView!)
webView?.allowsBackForwardNavigationGestures = true
webView?.navigationDelegate = self
let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(myViewController.handleSwipes(_:)))
let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(myViewController.handleSwipes(_:)))
leftSwipe.direction = .Left
rightSwipe.direction = .Right
view.addGestureRecognizer(leftSwipe)
view.addGestureRecognizer(rightSwipe)
}
override func viewDidAppear(animated: Bool) {
let frame = CGRectMake(0, 0, container.bounds.width, container.bounds.height)
webView!.frame = frame
let url = NSURL(string: "https://www.google.com")
let request = NSURLRequest(URL: url!)
self.webView!.loadRequest(request)
}
#IBAction func buttonClick(sender: AnyObject) {
webView?.evaluateJavaScript("document.getElementByID('hplogo').style.backgroundColor='red';", completionHandler: nil)
}
func handleSwipes(sender:UISwipeGestureRecognizer){
if (sender.direction == .Left){
webView?.evaluateJavaScript("document.getElementByID('hplogo').style.backgroundColor='black';", completionHandler: nil)
}
if (sender.direction == .Right){
webView?.evaluateJavaScript("document.getElementByID('hplogo').style.backgroundColor='green';", completionHandler: nil)
}
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
webView?.evaluateJavaScript("document.getElementByID('hplogo').style.backgroundColor='red';", completionHandler: nil)
}
}
You misspelled the Javascript's function name. It should be getElementById instead of getElementByID:
document.getElementById('hplogo').style.backgroundColor = '...'

Activity indicator swift

I'm trying to set up an activity indicator on my TableView where is my news feed is displayed. So I want that idicator to appear whenever load starts and disappear when it ends.
I know there is a function for webView like this:
func webViewDidFinishLoad(webView: UIWebView) {
activityView.removeFromSuperview()
}
func webViewDidStartLoad(webView: UIWebView) {
self.view.addSubview(activityView)
}
But it won't work for Table View obviously. Can someone suggest a solution?
I've tried to apply an activity indicator both in the center of my screen and in my Status bar but to no succsess.
I can add full code of my TableView controller if needed.
Thank you!
EDIT
override func viewDidLoad() {
super.viewDidLoad()
// Cell height.
self.tableView.rowHeight = 70
self.tableView.dataSource = self
self.tableView.delegate = self
url = NSURL(string: "http---")!
//url = NSURL(string: "http---")!
//url = NSURL(string: "http---")!
loadRss(url);
To show the small activity indicator in the status bar
func webViewDidFinishLoad(webView: UIWebView) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
func webViewDidStartLoad(webView: UIWebView) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
show the small activity
This is links you can see the answer

Progress bar while webView loading

I want to make that when tableView row tapped and opens the webView screen my progressBar appears with the value 0.3. Later it progress +0.1 and when it loaded it becomes 1 and hide it.
What I do:
progressBar.progress = 0.3
myWebView.loadHTMLString(body, baseURL: nil)
progressBar.progress = 1
It loads immediately full progress on tap. How can I do it? Must I turn off async?
UPDATE
I did also
func webViewDidStartLoad(webView: UIWebView) {
progressBar.progress = 0.2
}
func webViewDidFinishLoad(webView: UIWebView) {
progressBar.progress = 1
}
but it doesn't work. It stays in some position
UPDATE 2
They did not call yet. I wrote println inside of these functions and nothing printed
You better see this tutorial: http://www.ioscreator.com/tutorials/progress-view-tutorial-in-ios8-with-swift
Well, your mistake in the code is:
When 'webViewDidStartLoad' will be called then progress bar will increase to 0.2%, that's fine! Because its the initial point. But when you are going to increase to 0.2 - 0.4 or 0.2 - 0.3, for that you have to run as an Async task. So, please look at the tutorial and increase the counter accordingly.
Hope you got it!
I just drag from my webView and delegate it with my viewController and it works now!
Try this out
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "https://topdigital.agency")
let request = NSURLRequest(url: url as! URL)
webView.loadRequest(request as URLRequest)
webView.delegate=self
}
func webViewDidStartLoad(_ webView: UIWebView) {
self.progressView.setProgress(0.1, animated: false)
}
func webViewDidFinishLoad(_ webView: UIWebView) {
self.progressView.setProgress(1.0, animated: true)
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
self.progressView.setProgress(1.0, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

Resources