0

我创建了一个实现 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()
}
4

1 回答 1

0

实现这一点的最佳方法可能是NSNotification在匹配 URL 时从您的协议中发布一个。

CUrlProtocol中,当您找到匹配项时(通知名称可以由您选择):

let notification:NSNotification = NSNotification(name: "MyURLMatchedNotification", object: nil)
NSNotificationCenter.defaultCenter().postNotification(notification)

在你的WebViewController

// During init (or viewDidAppear, if you only want to do it while its on screen)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "getUserToken", name: "MyURLMatchedNotification", object: nil)

...

// During dealloc (or viewWillDisappear)
NSNotificationCenter.defaultCenter().removeObserver(self, name: "MyURLMatchedNotification", object: nil)

如果您需要来自该请求的信息,您也可以在通知中传递一些信息。只需object在创建通知时设置参数并将您的更改getUserToken为接受具有类型的单个参数NSNotification并访问其object属性。

于 2015-10-05T16:26:25.160 回答