xcode Swift 中的进度条 WebView

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28147096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:32:06  来源:igfitidea点击:

Progressbar WebView in Swift

iosxcodeswiftwebviewuiwebview

提问by Mirko Brombin

I'm writing a webapp in swift with xcode. I've a question "How can I add a progressbar that shows me the loading of each page?"

我正在使用 xcode 快速编写一个 web 应用程序。我有一个问题“如何添加一个进度条来显示每个页面的加载情况?”

@IBOutlet var webView: UIWebView!
override func viewDidLoad() {
   super.viewDidLoad()
   let url = NSURL(string: "http://stackoverflow.com")
   let request = NSURLRequest(URL: url)
   webView.loadRequest(request)
}

(Sorry for my english)

(对不起我的英语不好)

回答by Starscream

You can find a very good answer in this post. You can just add a progress bar as a subview to your webview. The main problem is the accuracy of the progress bar. The proposed answer is to begin by animating it constantly, block it at 95% when still loading and when your request is complete, zip it all the way to 100%.

你可以在这篇文章中找到一个很好的答案。您可以将进度条作为子视图添加到您的 web 视图中。主要问题是进度条的准确性。建议的答案是从不断地动画开始,在仍然加载时将其阻止在 95%,当您的请求完成时,将其一直压缩到 100%。

Here's a solution in Swift:

这是 Swift 中的解决方案:

Add these properties:

添加这些属性:

//Add this progress view via Interface Builder (IBOutlet) or programatically
let myProgressView: UIProgressView

var theBool: Bool
var myTimer: NSTimer

These functions will fill the progress view. You can play with the parameters:

这些函数将填充进度视图。您可以使用以下参数:

func funcToCallWhenStartLoadingYourWebview() {
    self.myProgressView.progress = 0.0
    self.theBool = false
    self.myTimer = NSTimer.scheduledTimerWithTimeInterval(0.01667, target: self, selector: "timerCallback", userInfo: nil, repeats: true)
}

func funcToCallCalledWhenUIWebViewFinishesLoading() {
    self.theBool = true
}

func timerCallback() {
    if self.theBool {
        if self.myProgressView.progress >= 1 {
            self.myProgressView.hidden = true
            self.myTimer.invalidate()
        } else {
            self.myProgressView.progress += 0.1
        }
    } else {
        self.myProgressView.progress += 0.05
        if self.myProgressView.progress >= 0.95 {
            self.myProgressView.progress = 0.95
        }
    }
}

回答by alemac852

    var theBool: Bool
    var myTimer: NSTimer
    var didFinishTimer: NSTimer


    required init(coder aDecoder: NSCoder) {
        self.theBool = false
        self.myTimer = NSTimer()
        self.didFinishTimer = NSTimer()

        super.init(coder: aDecoder)
    }
           func startAnimatingProgressBar() {
            self.theBool = false
            myProgressView.hidden = false
            myProgressView.alpha = 0
            UIView.animateWithDuration(0.2, animations: { () -> Void in
                self.myProgressView.alpha = 0.6
            })
            self.myProgressView.progress = 0.0

            //Tweek this number to alter the main speed of the progress bar
            var number = drand48() / 80;
//            println("startAnimatingProgressBar|\(number)")

            self.myTimer = NSTimer.scheduledTimerWithTimeInterval(number, target: self, selector: "timerCallback", userInfo: nil, repeats: true)
//            println("myTimer|\(myTimer)")
    }

    func finishAnimatingProgressBar() {
        self.theBool = true
    }

    func timerCallback() {
        if self.theBool {
            if self.myProgressView.progress >= 1 {
                UIView.animateWithDuration(0.2, animations: { () -> Void in
                    self.myProgressView.alpha = 0

//                    }, completion: { (success:Bool) -> Void in
//                        self.myProgressView.hidden = true
                })
                self.myTimer.invalidate()
            } else {
                //Loaded and zoom to finish
                var number = drand48() / 40
//                println("finished:\(number)")

                self.myProgressView.progress += Float(number)
            }

        } else {
            //Start slow
            if self.myProgressView.progress >= 0.00 && self.myProgressView.progress <= 0.10 {
                var number = drand48() / 8000;
//                println("Start:\(number)")

                self.myProgressView.progress += Float(number)
                //Middle speed up a bit
            } else if self.myProgressView.progress >= 0.10 && self.myProgressView.progress <= 0.42 {
                var smallerNumber = drand48() / 2000;
                self.myProgressView.progress += Float(smallerNumber)
//                println("Middle:\(smallerNumber)")

                //slow it down again
            } else if myProgressView.progress >= 0.42 && self.myProgressView.progress <= 0.80 {
                var superSmallNumber = drand48() / 8000;
                self.myProgressView.progress += Float(superSmallNumber)
//                println("slow it down:\(superSmallNumber)")

                //Stop it
            } else if myProgressView.progress == 0.80 {
                println("Stop:\(myProgressView.progress)")
                self.myProgressView.progress = 0.80
            }
        }
    }


    var webViewLoads = 0
    var webViewDidStart:Int = 0
    var webViewDidFinish:Int = 0

  func webViewDidStartLoad(webView: UIWebView) {


    webViewDidStart++
    webViewLoads++

    if webViewLoads <= 1 {
        startAnimatingProgressBar()
    }

    println("webViewDidStartNumber: = \(webViewDidStart)")
    println("webViewLoadsStart: = \(webViewLoads)")

//    println("webViewDidStartLoad")

    UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    updateToolbarItems()
  }

  func webViewDidFinishLoad(webView: UIWebView) {

        webViewLoads--
        webViewDidFinish++

        println("webViewDidFinishLoad \(webViewDidFinish)")

    if webViewLoads == 0 {
        finishAnimatingProgressBar()
//        println("webViewLoads \(webViewLoads)")
        return
    }
    getWebsiteInfo()
    UIApplication.sharedApplication().networkActivityIndicatorVisible = false

    updateToolbarItems()

  func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
    theBool = true
    webViewLoads = 0
    UIApplication.sharedApplication().networkActivityIndicatorVisible = false

    println("didFailLoadWithError")

    updateToolbarItems()
  }

Took me ages to figure out how to determine when a website has fully loaded and animate the progress bar according... after some hardcore googling this is the best I could come up with. lots of people saying lots of stuff most of it didn't help me.... add, and improve please let me know if you figure out something better.

我花了很长时间才弄清楚如何确定网站何时完全加载并根据...为进度条设置动画......经过一些铁杆谷歌搜索后,这是我能想到的最好的方法。很多人说了很多东西,其中大部分对我没有帮助....添加和改进如果你想出更好的东西,请告诉我。

回答by nfinfu

I am using this and looks good.

我正在使用这个,看起来不错。

@IBOutlet var webView: UIWebView!
@IBOutlet var progressView: UIProgressView!
override func viewDidLoad() {
   super.viewDidLoad()
   let url = NSURL(string: "http://stackoverflow.com")
   let request = NSURLRequest(URL: url)
   webView.loadRequest(request)
   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: NSError?) {

    self.progressView.setProgress(1.0, animated: true)
}

回答by Ram

Why not use

为什么不使用

loadRequest(_ request: URLRequest, progress: ((UInt, Int64, Int64) -> Swift.Void)?, success: ((HTTPURLResponse, String) -> String)?, failure: ((Error) -> Swift.Void)? = nil)

loadRequest(_ request: URLRequest, progress: ((UInt, Int64, Int64) -> Swift.Void)?, success: ((HTTPURLResponse, String) -> String)?, failure: ((Error) -> Swift.Void)? = nil)