Skip to content

Instantly share code, notes, and snippets.

@ivanbruel
Created April 9, 2015 17:26
Show Gist options
  • Save ivanbruel/f098c465e0ebae444f63 to your computer and use it in GitHub Desktop.
Save ivanbruel/f098c465e0ebae444f63 to your computer and use it in GitHub Desktop.
Swift Class Method Swizzle
//
// LHNetworking+Endpoint.swift
// magellan
//
// Created by Ivan Bruel on 09/04/15.
// Copyright (c) 2015 Passworks S.A. All rights reserved.
//
import Foundation
import Lighthouse
extension LHNetworking {
public override class func initialize() {
struct Static {
static var token: dispatch_once_t = 0
}
// make sure this isn't a subclass
if self !== LHNetworking.self {
return
}
dispatch_once(&Static.token) {
let originalSelector = Selector("endpoint")
let swizzledSelector = Selector("lh_endpoint")
if let klass: AnyClass = object_getClass(self) {
let originalMethod = class_getClassMethod(klass, originalSelector)
let swizzledMethod = class_getClassMethod(klass, swizzledSelector)
let didAddMethod = class_addMethod(klass, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(klass, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
}
}
// MARK: - Method Swizzling
class func lh_endpoint() -> String! {
let environmentDictionary = NSProcessInfo.processInfo().environment
if let endpoint = environmentDictionary["ENDPOINT"] as? String {
println("returning custom endpoint \(endpoint)")
return endpoint
}
return self.lh_endpoint()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment