我创建了一个实现 NSURLProtocol 的类,它将告诉我有关 UIWebView 请求的信息。我希望告诉 UI 我们点击了感兴趣的 URL,并在 ViewController 上运行代码以访问 WebView。
我相信协议(protocol)是解决方案,但我似乎无法思考如何让它发挥作用。任何建议和代码示例将不胜感激。这是我到目前为止所尝试过的。
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")
}
}
这是我的 NSURLProtocol 实现的类以及尝试的协议(protocol)(请告诉我它是否是错误的方法)
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()
}
最佳答案
实现此目的的最佳方法可能是在匹配 URL 时从协议(protocol)中发布 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
的单个参数并访问其 对象
属性。
关于iOS Swift 如何告诉 UIView Controller 我们通过 NSURLProtocol 对象接收到信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32893267/