Skip to content

Instantly share code, notes, and snippets.

@nallwhy
Last active January 7, 2017 10:14
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 nallwhy/6dca541a2d1d468e0be03c97add384de to your computer and use it in GitHub Desktop.
Save nallwhy/6dca541a2d1d468e0be03c97add384de to your computer and use it in GitHub Desktop.
HTTP
//
// HttpClient.swift
// Secretvill
//
// Created by Jinkyou Son on 2017. 1. 6..
// Copyright © 2017년 ultramarine. All rights reserved.
//
import Alamofire
import ReactiveKit
import ReactiveAlamofire
class HttpClient {
static private var API_HOST: String {
return SOME_HOST
}
static func get<T>(path: String, params: [String : AnyObject] = [:]) -> SafeSignal<JSONResponse<T>> {
return self.request(method: .get, path: path, params: params)
}
static private func request<T>(method: Alamofire.HTTPMethod, path: String, params: [String : AnyObject], headers: [String : String]? = nil) -> SafeSignal<JSONResponse<T>> {
let uri = "\(API_HOST)\(path)"
return Alamofire.request(uri, method: method, parameters: params, headers: headers)
.toJSONSignal()
.flatMapError { error in
return SafeSignal.just(["errors" : [["code": "인터넷 연결을 확인해주세요."]]])
}
.map { (json: Any) -> JSONResponse<T> in
print(json)
return self.parseResponse(json)
}
}
static private func parseResponse<T>(_ json: Any?) -> JSONResponse<T> {
var result: JSONResponse<T>? = nil
if let json = json as? [String : Any] {
if IS_ARRAY {
} else {
}
}
return result ?? .failure(errors: [["code": "Unexpected response"]])
}
}
public enum JSONResponse<T> {
case success(data: T, meta: [String : Any]?)
case failure(errors: [[String : String]]?)
}
class Post: Mappable {
private var id: Int
private var title: String
private var description: String
}
import UIKit
import ReactiveKit
class ViewController: UIViewController {
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
HttpClient.get(path: "/posts/all")
.observeNext { (response: JSONResponse<[Post]>) in
print(response.message)
}.dispose(in: disposeBag)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
@devxoul
Copy link

devxoul commented Jan 7, 2017

enum JSONResponse<T> {
  case success(T)
  case failure
}

protocol Mappable {
  init?(dictionary: [String: Any])
}

struct Post: Mappable {
  var id: Int
  init?(dictionary: [String: Any]) {
    guard let id = dictionary["id"] as? Int else { return nil }
    self.id = id
  }
}

func parseResponse<T: Mappable>(_ json: Any?) -> JSONResponse<T>? {
  guard let dictionary = json as? [String: Any] else { return nil }
  return T.init(dictionary: dictionary).flatMap(JSONResponse.success)
}

func parseResponse<T: Mappable>(_ json: Any?) -> JSONResponse<[T]>? {
  guard let array = json as? [[String: Any]] else { return nil }
  return .success(array.flatMap(T.init))
}

let dictionary: [String: Any] = ["id": 1]
let post: JSONResponse<Post>? = parseResponse(dictionary)
print("post: \(post)") // .success(Post(id: 1))

let array: [[String: Any]] = [["id": 1], ["id": 2]]
let posts: JSONResponse<[Post]>? = parseResponse(array)
print("posts: \(posts)") // .success([Post(id: 1), Post(id: 2)])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment