我创建了一个实现 NSURLProtocol 的类,它将告诉我有关 UIWebView 请求的信息。我希望告诉 UI 我们点击了感兴趣的 URL 并在 ViewController 上运行代码以访问 WebView。
我相信协议是解决方案,但似乎无法解决如何让它发挥作用。任何建议和代码示例将不胜感激。这是我到目前为止所尝试的。
UI 视图 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")
}
}
这是我的 NSURLProtocol 实现的类以及尝试的协议(如果它是错误的方法,请告诉我)
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()
}