dispatch_async UIWebView loadrequest

时间:2015-02-08 01:34:20

标签: ios swift uiwebview nstimer dispatch-async

我正在加载我的应用程序中的javascript,该脚本将尝试找到解决方案,这可能需要一些时间。我不想为该解决方案等待超过5秒,在这种情况下,我只想停止请求并向用户显示消息。

我一直在尝试使用NSTimers和dispatch_async,但是UIWebView请求仍在使用我的整个主队列,并且在此期间我停止了NSTimer我正在等待答案。

请求电话:

webViewUIView.delegate = self

var path = NSBundle.mainBundle().pathForResource("page", ofType: "html")

var url = NSURL(fileURLWithPath: path!)
var req = NSURLRequest(URL:url!)
var queue = NSOperationQueue()

 dispatch_async(dispatch_get_main_queue()) {
    println("********CALLING TO LOADREQUEST")

    self.webViewUIView.loadRequest(req)
 }                    

我的NSTimer:

var timer2 = NSTimer()

func webViewDidStartLoad(webView: UIWebView) {
    println("********Creating the Timer")
    let aSelector : Selector = "cancelWeb"
    self.timer2 = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: aSelector, userInfo: nil, repeats: false)
    println("After create the timer")

}

cancelWeb:

func cancelWeb(){

        println("****Before Stop Load")
        webViewUIView.stopLoading()
        println("After stopLoading")
        timer2.invalidate()

}

我的webViewDidFinishLoad:

 func webViewDidFinishLoad(webView: UIWebView) {

        webViewUIView.stringByEvaluatingJavaScriptFromString("func('\(obj)')")

        let result: String = webViewUIView.stringByEvaluatingJavaScriptFromString("document.getElementById('log').innerText")!

        timer2.invalidate()
...
...

当我运行应用程序时,即使在Timer中设置了5秒后,该过程仍在运行,我只看到这个问题:关于创建TImer,After Timer和CALLING TO LOADREQUEST。

有关如何与NSTimer同时并行运行请求的任何想法?如您所见,调度不起作用,可能是因为URL在同一个Bundle中?

嗯,与此同时我正在等待解决方案,应用程序被冻结,等待答案......这可能需要花费很长时间。

在请求中使用超时是行不通的,因为连接是正确建立的,事情是需要很长时间才能收到答案。

谢谢费拉斯!

2 个答案:

答案 0 :(得分:0)

代码中缺少另一个UIWebView委托func。您可能需要在

中添加timer2.invalidate()
func webView(_ webView: UIWebView,
 didFailLoadWithError error: NSError)

答案 1 :(得分:0)

好的,我在我的Javascript代码中创建了一个Worker,所以我可以像新线程一样处理它,但不能在iOS中处理(使用UIWebView是不可能的)。解决方案如下:iOS Javascript Workers High CPU after terminate()

相关问题