Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
import Alamofire
import RxSwift
/**
API通信をするためのプロトコル
- parameters: パラメーターを指定
- baseURL: APIのドメインを指定
- path: APIのパスを指定
- method: CRUDを指定
*/
protocol APIRequest {
var parameters: [String: AnyObject] { get }
var baseURL: String { get }
var path: String { get }
var method: Alamofire.Method { get }
}
extension APIRequest {
/// API通信の対象URL
var url: String { return baseURL + path }
/**
API通信を実行する
- returns: Observable:AnyObject
- throws: Observable:ErrorType
*/
func request() -> Observable<AnyObject> {
return Observable.create { observer in
let request = Alamofire.request(self.method, self.url, parameters: self.parameters, encoding: .URL)
.responseJSON { response in
switch response.result {
case .Success:
observer.onNext(response.result.value!)
observer.onCompleted()
case .Failure(let error):
observer.onError(error)
}
}
request.resume()
return AnonymousDisposable {
request.cancel()
}
}
}
}
import Alamofire
/**
EventのAPI通信情報を設定
*/
enum EventsRequest {
case GetEvents(Int)
}
extension EventsRequest: APIRequest {
var baseURL: String { return GlobalConstant.atndBase }
var method: Alamofire.Method {
switch self {
case .GetEvents:
return .GET
}
}
var path: String {
switch self {
case .GetEvents:
return GlobalConstant.atndEvents
}
}
var parameters: [String: AnyObject] {
switch self {
case .GetEvents(let count):
return [
"format": "json",
"start": count,
"count": 15
]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment