この組み合わせの例がまだ少なかったので
環境
- swift 3.0
- Almofire 4.0.1
- xcode 8.0
汎用的に利用するためのサンプル
ApiManager.swift
import Alamofire
private let host = "https://example.com"
struct ApiManager {
let url: String
let method: HTTPMethod
let parameters: Parameters
init(path: String, method: HTTPMethod = .get, parameters: Parameters = [:]) {
url = host + path
self.method = method
self.parameters = parameters
}
func request(success: @escaping (_ data: Dictionary<String, Any>)-> Void, fail: @escaping (_ error: Error?)-> Void) {
Alamofire.request(url, method: method, parameters: parameters).responseJSON { response in
if response.result.isSuccess {
success(response.result.value as! Dictionary)
}else{
fail(response.result.error)
}
}
}
}
使う側
let api = ApiManager(path: "/users.json")
api.request(success: { (data: Dictionary) in debugPrint(data) }, fail: { (error: Error?) in print(error) })
swift初めて書くので指摘あれば編集リクエスト下さい。