I created a class that implements NSURLProtocol which will tells me about the UIWebView requests. I am looking to tell the UI that we hit a URL of interest and run code back on the ViewController to access the WebView.
I believe Protocols are the solution but cant seem to wrap my head around how to get this to work. Any suggestions and code example would be much appreciated. Here is what I've tried so far.
UI View Controller.swift
class WebViewController: UIViewController,WebAuthDelegate {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://example.com")
let request = NSURLRequest(URL: url!)
webView.loadRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onBackClick(sender: AnyObject) {
if(webView.canGoBack){
webView.goBack()
}
}
@IBAction func onFwdClick(sender: AnyObject) {
if(webView.canGoForward){
webView.goForward()
}
}
@IBAction func onRefresh(sender: AnyObject) {
webView.reload()
}
func getUserToken() {
print("RUN THIS AFTER I HIT URL IN URL PROTOCAL CLASS")
}
}
Here is my NSURLProtocol implemented class along with the attempted protocol(which please tell me if its the wrong approach)
class CUrlProtocol: NSURLProtocol {
//let delegate: WebAuthDelegate? = nil
override class func canInitWithRequest(request: NSURLRequest) -> Bool {
print("URL = \(request.URL!.absoluteString)")
if request.URL!.absoluteString == "http://api-dev.site.com/token" {
//Tell the UI That we now have the info and we can access the UIWebView Object
}
return false
}
}
protocol WebAuthDelegate{
func getUserToken()
}