iOS Swift如何告诉UIView Controller我们通过NSURLProtocol对象

时间:2015-10-01 17:18:59

标签: ios swift uiwebview nsurlprotocol

我创建了一个实现NSURLProtocol的类,它将告诉我UIWebView请求。我希望告诉用户界面我们点击了一个感兴趣的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()
}

1 个答案:

答案 0 :(得分:0)

实现此目标的最佳方法可能是在匹配网址时从协议发布NSNotification

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属性。