路由实现如下:
import Alamofire
struct Router {
static let baseUrlString = "https://www.v2ex.com"
}
enum V2exNodeRouter: URLRequestConvertible {
case all
case one(name:String, id:String)
case favNode(name:String)
func asURLRequest() throws -> URLRequest {
var method: HTTPMethod {
switch self {
case .all, .favNode,.one:
return .get
}
}
let url:URL = {
let relativePath: String
switch self {
case .all:
relativePath = "/api/nodes/all.json"
case .one:
relativePath = "/api/nodes/show.json"
case .favNode(let nodeName):
relativePath = "/go/\(nodeName)"
}
var url = URL(string: Router.baseUrlString)!
url.appendPathComponent(relativePath)
return url
}()
let params: ([String: Any]?) = {
switch self {
case .all, .favNode:
return nil
case .one(let name, let id):
if name.length > 0 {
return ["node_name": name]
}
if id.length > 0 {
return ["node_id": id]
}
if name.length > 0 && id.length > 0 {
return ["node_name": name]
}
return nil
}
}()
print(url)
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = method.rawValue
let encoding = JSONEncoding.default
return try encoding.encode(urlRequest, with: params)
}
}
service Manger如下所示:
typealias CompletionCallbackBlcok = (_ response: Any?, _ error: Error?) ->Void
class V2exServiceManager: NSObject {
static let shared: V2exServiceManager = {
let instance = V2exServiceManager()
return instance
}()}
网络请求方法如下所示:
extension V2exServiceManager {
func getAllNodes(_ all: V2exNodeRouter, completionHander: @escaping (Result<[V2exNode]>) -> Void) {
Alamofire.request(all)
.responseJSON { (dataResponse) in
if let result = dataResponse.value {
print(result)
}
}
}
func getNode(_ one: V2exNodeRouter, completionHander: @escaping (Result<[V2exNode]>) -> Void) {
Alamofire.request(one)
.responseString { (response) in
print(response)
}
}
func favNodeWithName(_ favNode: V2exNodeRouter, completionHander: @escaping (Result<[V2exNode]>) -> Void) {
Alamofire.request(favNode)
.responseString { (response) in
print(response)
}
}
}
调用如下所示
V2exServiceManager.shared.getAllNodes(V2exNodeRouter.all) { (result) in
}
V2exServiceManager.shared.getNode(V2exNodeRouter.one(name: "babel", id: "1")) { (result) in
}
V2exServiceManager.shared.favNodeWithName(V2exNodeRouter.favNode(name: "babel")) { (result) in
}