Skip to content

Instantly share code, notes, and snippets.

@YutoMizutani
Created September 19, 2018 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YutoMizutani/8844631bbea6fdb47e78ea3e36d45221 to your computer and use it in GitHub Desktop.
Save YutoMizutani/8844631bbea6fdb47e78ea3e36d45221 to your computer and use it in GitHub Desktop.
Genericsを用いて安全にJSONをパースする (Alamofire x Swift4) ref: https://qiita.com/YutoMizutani/items/c61fbb0060095939e7ff
import Alamofire
class Foo {
/// Success handler
public typealias SuccessHandler<T> = (_ model: T) -> Void
/// Failure handler
public typealias FailureHandler = (_ error: Error) -> Void
/**
Alamofire Request
- Parameters:
- url: API URL
- method: HTTP method
- parameters: Query parameters
- success: Success handler
- failure: Failure handler
*/
func baseRequest<T: Decodable>(_ url: String,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
success: SuccessHandler<T>?,
failure: FailureHandler?) {
Alamofire.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers)
.responseData { response in
switch response.result {
case .success:
guard let success = success, let data = response.data else { return }
let decoder: JSONDecoder = JSONDecoder()
guard let model = try? decoder.decode(T.self, from: data) else { return }
success?(model)
case .failure(let error):
failure?(error)
}
}
}
}
public struct FooModel: Codable {
public let bar: String
}
func request(_ url: String,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
success: SuccessHandler<FooModel>?,
failure: FailureHandler?) {
self.baseRequest(url,
method: method,
parameters: parameters,
success: success,
failure: failure)
}
self.request(url, success: { fooModel in
print(fooModel.bar)
})
import XCTest
@testable import Foo
final class FooTests: XCTestCase {
var foo: Foo!
override func setUp() {
super.setUp()
self.foo = Foo()
}
func decode<T: Decodable>(_ url: String, parameters: Parameters?, model: T.Type) {
let expect: XCTestExpectation = self.expectation(description: url)
let success: Foo.SuccessHandler<T> = { model in
expect.fulfill()
XCTAssertNotNil(model)
}
let failure: Foo.FailureHandler = { error in
expect.fulfill()
XCTFail(error.localizedDescription)
}
self.foo.baseRequest(url, success: success, parameters: parameters, failure: failure)
self.wait(for: [expect], timeout: 10)
}
}
func testDecodeFoo() {
decode(url, parameters: parameters. model: FooModel.self)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment