Skip to content

Instantly share code, notes, and snippets.

@backslash-f
Last active November 23, 2016 04:04
Show Gist options
  • Save backslash-f/5d3fb6e050503acfa8cd6506b1a36093 to your computer and use it in GitHub Desktop.
Save backslash-f/5d3fb6e050503acfa8cd6506b1a36093 to your computer and use it in GitHub Desktop.
JSON to AnyObject from a .json file
import Foundation
/// Mocks network responses. Useful to be used with Unit/UI tests.
class ResponseMocker {
/// Returns a mocked `JSON` object encapsulated in an `AnyObject`,
/// representing a mocked endpoint response.
///
/// - returns: A mocked `JSON` object encapsulated in an `AnyObject`,
/// representing a Notice root endpoint response.
class func mockedEndpoint() -> Data {
return retrieveDataFrom(filename: "MockedEndpoint")!
}
/// Reads a `JSON` file using the name passed in as parameter, converts and
/// returns it as `AnyObject` - if the file exists. Otherwise, or if any
/// error during the conversion, returns nil.
///
/// - parameter filename: the `JSON` filename to be read.
///
/// - returns: A `JSON` object in `AnyObject` format - or nil if the file
/// does not exist or if any error during the conversion.
class func retrieveDataFrom(filename: String) -> Data? {
// First, find the file.
if let path = Bundle.main.path(forResource: filename, ofType: "json"),
let data = NSData(contentsOfFile: path) {
do {
// Convert it to JSON data.
let jsonData = try JSONSerialization.jsonObject(
with: data as Data,
options: .mutableContainers
)
// Convert it to Data.
let data = try JSONSerialization.data(
withJSONObject: jsonData,
options: .prettyPrinted
)
// Return.
return data
} catch {
print("Could not read the file or its contents.")
}
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment