Search code examples
iosxcodeswiftunrecognized-selector

WKWebView.loading returns unrecognized selector


I run a timer that looks like this:

else if label == "Instagram" && defaults.boolForKey("instagramswitch") {
            activeWebview.loadRequest(request)
            let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
            dispatch_after(dispatchTime, dispatch_get_main_queue(), {
                self.i = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("instagram:"), userInfo: activeWebview, repeats: true)
            })
}

and the function looks like this:

func instagram(webview: WKWebView) {
    if webview.loading == false {
        let code: String = "document.getElementsByClassName('2yal _csflf').item(3).click();"
        webview.evaluateJavaScript(code, completionHandler: nil)
        let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
        dispatch_after(dispatchTime, dispatch_get_main_queue(), {
            self.i = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("instagramloaded:"), userInfo: webview, repeats: true)
        })
    }
}

I get an error on this line - "if webview.loading == false {" and the error is:

2016-04-10 15:16:53.679 PF 0.5[878:241174] -[__NSCFTimer isLoading]: unrecognized selector sent to instance 0x145a03fe0

Any and all help would be much appreciated :) I think it is because I call webview.loading but I have no idea why that would cause a crash.


Solution

  • You should modify the method like below,

    func instagram(timerObject: NSTimer) {
        if let webview = timerObject.userInfo as! WKWebView{
        if webview.loading == false {
            let code: String = "document.getElementsByClassName('2yal _csflf').item(3).click();"
            webview.evaluateJavaScript(code, completionHandler: nil)
            let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
            dispatch_after(dispatchTime, dispatch_get_main_queue(), {
                self.i = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("instagramloaded:"), userInfo: webview, repeats: true)
            })
        }
      }
    }
    

    Because the object in the argument is received as a NSTimer Object and you have to take out the data that you sent from the method call as the userInfo object. Hope this helps.