Last active
March 20, 2017 23:10
-
-
Save wwe-johndpope/60ac94a1af4537d755c71119d61f94f8 to your computer and use it in GitHub Desktop.
sample gist of OHHTTPStubs + API end points + local json files in bundle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import UIKit | |
import OHHTTPStubs | |
import SwiftyJSON | |
@objc class HTTPStub: NSObject { | |
static let enableHttpStubbing = HTTPStub() | |
override init() { | |
HTTPStub.stubHTTP() // N.B. when enabling do a clean | |
} | |
class func stubHTTP() { | |
OHHTTPStubs.setEnabled(true) | |
OHHTTPStubs.onStubActivation { (request: URLRequest, stub: OHHTTPStubsDescriptor, response: OHHTTPStubsResponse) in | |
if let url = request.url{ | |
print("[OHHTTPStubs] Request to \(url) has been stubbed stub:",stub.name ) | |
} | |
} | |
OHHTTPStubs.removeAllStubs() | |
stubLocalJsonForUrls() | |
} | |
class func stubLocalJsonForUrls(){ | |
// HARDCODED URLS + CORRESPONDING JSON FILES | |
let stubbedURLS:[[String : String]] = [ | |
["absoluteUrl":"http://www.example.com/get_cars?parameters=1","resource":"cars.json"], | |
["absoluteUrl":"http://www.example.com/get_cars?parameters=2","resource":"cars1.json"], | |
] | |
for d0 in stubbedURLS { | |
if var fileName = d0["resource"] { | |
if let uri = d0["absoluteUrl"] { | |
if fileName.contains("json") { | |
fileName = fileName.components(separatedBy: ".")[0] | |
} | |
let channelsPath = Bundle.main.path(forResource:fileName,ofType:"json") | |
let jsonURL = URL.init(fileURLWithPath: channelsPath!) | |
do{ | |
let data = try Data.init(contentsOf: jsonURL, options: Data.ReadingOptions.uncached) | |
let json = JSON(data: data) | |
let responseData = try json.rawData() | |
OHHTTPStubs.stubRequests(passingTest: { (request) -> Bool in | |
if let absoluteURL = request.url?.absoluteString{ | |
return( absoluteURL == uri ) | |
} | |
return false | |
}) { (request) -> OHHTTPStubsResponse in | |
if let url = request.url?.absoluteString{ | |
print("mocking local json:",url) | |
} | |
return OHHTTPStubsResponse(data:responseData , statusCode: 200, headers: ["Content-Type" : "application/json"]) | |
}.name = "Local Stubbed URLS" | |
}catch let jsonerror as NSError { | |
print("exception",jsonerror) | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment