Skip to content

Instantly share code, notes, and snippets.

@cliss
Created March 29, 2016 13:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cliss/91dbceb77f39e092f062 to your computer and use it in GitHub Desktop.
Save cliss/91dbceb77f39e092f062 to your computer and use it in GitHub Desktop.
Reactive Extensions for UIWebView
//
// RxUIWebViewDelegateProxy.swift
//
// Created by Casey Liss on 24/3/16.
// Copyright © 2016 Casey Liss. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
class RxUIWebViewDelegateProxy: DelegateProxy, UIWebViewDelegate, DelegateProxyType {
class func currentDelegateFor(object: AnyObject) -> AnyObject? {
let webView: UIWebView = (object as? UIWebView)!
return webView.delegate
}
class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) {
let webView: UIWebView = (object as? UIWebView)!
webView.delegate = delegate as? UIWebViewDelegate
}
}
//
// UIWebView+Rx.swift
//
// Created by Casey Liss on 24/3/16.
// Copyright © 2016 Casey Liss. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
// This file is largely inspired by:
// https://github.com/RxSwiftCommunity/RxMKMapView/blob/master/Pod/Classes/MKMapView%2BRx.swift
// Taken from RxCococa until marked as public
func castOrThrow<T>(resultType: T.Type, _ object: AnyObject) throws -> T {
guard let returnValue = object as? T else {
throw RxCocoaError.CastingError(object: object, targetType: resultType)
}
return returnValue
}
extension UIWebView {
/**
Reactive wrapper for `delegate`.
For more information, take a look at `DelegateProxyType` protocol documentation.
*/
public var rx_delegate: DelegateProxy {
return proxyForObject(RxUIWebViewDelegateProxy.self, self)
}
/**
Signaled after a web view starts loading a frame.
*/
public var rx_didStartLoad: ControlEvent<Void> {
let source = rx_delegate.observe(#selector(UIWebViewDelegate.webViewDidStartLoad(_:))).map { _ in return() }
return ControlEvent(events: source)
}
/**
Signaled after a web view finishes loading a frame.
*/
public var rx_didFinishLoad: ControlEvent<Void> {
let source = rx_delegate.observe(#selector(UIWebViewDelegate.webViewDidFinishLoad(_:))).map { _ in return() }
return ControlEvent(events: source)
}
/**
Signaled when a web view failed to load a frame.
*/
public var rx_didFailLoad: ControlEvent<NSError> {
let source = rx_delegate.observe(#selector(UIWebViewDelegate.webView(_:didFailLoadWithError:))).map { error in
return try castOrThrow(NSError.self, error[1])
}
return ControlEvent(events: source)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment