譯:
在這篇文章中,我將討論我之前在程序開發中使用的可以讓iOS程序更加健壯的重用類。最近,我需要一個導航路由類來解決網絡請求不同類型的URL,;例如:.GET .POST .PUT DELETE HTTP等等。
用一個單獨的類來處理網絡任務很??,所以要自定義路由,這是基于Alamofire實現的。

什么是路由
路由是一種面向對象的方法來處理API / Microservice urls,但是他本身用枚舉的形式。也就是采用枚舉中的URL請求方法進行網絡請求,無縫的同意和簡化了網絡路由。
參考文章:如何為Alamofire創建路由
創建路由協議
首先創建一個RouterProtocol
協議,用來兼容REST的四種請求方法(get、post、update、destroy)。
// MARK: - Router
protocol RouterProtocol {
var apiType: ApiType { get set }
func post() -> String
func get(identifier: String) -> String
func update(identifier: String) -> String
func destroy(identifier: String) -> String
}
struct AccountsRouter: RouterProtocol {
var apiType = ApiType.Accounts
func post() -> String { return apiType.route }
func get(identifier: String) -> String { return "\(apiType.route)/\(identifier)" }
func update(identifier: String) -> String { return "\(apiType.route)/\(identifier)" }
func destroy(identifier: String) -> String { return "\(apiType.route)/\(identifier)" }
}
然后定義一個Router
的枚舉:
首先,遵守
RouterProtocol
,調用方法;Router
枚舉必須是泛型,用以接收所用遵守RouterProtocol
的結構體;為四種接收方法(.GET .POST .PUT .DELETE)定義方法、路徑和路由屬性;
創建
NSMutableURLRequest
的屬性URLRequest
,用來添加通用的配置,比如方法名、默認請求頭、用戶token等等;-
最后使用
Alamofire
的參數編碼進行編碼。//
// Router.swift
//
// Created by Seyhun Akyürek on 01/10/2016.
// Copyright ? 2016 seyhunak. All rights reserved.
//
import Foundation
import Alamofire// MARK: - Router
protocol RouterProtocol {
var apiType: ApiType { get set }
func post() -> String
func get(identifier: String) -> String
func update(identifier: String) -> String
func destroy(identifier: String) -> String
}enum Router<T where T: RouterProtocol>: URLRequestConvertible {
case post(T, [String: AnyObject]) case get(T, String) case update(T, String, [String: AnyObject]) case destroy(T, String) var method: Alamofire.Method { switch self { case .post: return .POST case .get: return .GET case .update: return .PUT case .destroy: return .DELETE } } var path: NSURL { switch self { case .post(let object, _): return object.apiType.path case .get(let object): return object.0.apiType.path case .update(let object): return object.0.apiType.path case .destroy(let object): return object.0.apiType.path } } var route: String { switch self { case .post(let object, _): return object.post() case .get(let object, let identifier): return object.get(identifier) case .update(let object, let identifier, _): return object.update(identifier) case .destroy(let object, let identifier): return object.destroy(identifier) } } // MARK: - URLRequestConvertible var URLRequest: NSMutableURLRequest { let task = NSURLSession.sharedSession().dataTaskWithURL(path) { (data, response, error) in if error != nil { return } } task.resume() let mutableURLRequest = NSMutableURLRequest(URL: path.URLByAppendingPathComponent(route)) mutableURLRequest.HTTPMethod = method.rawValue mutableURLRequest.timeoutInterval = NSTimeInterval(10 * 1000) if let token = oauthToken { mutableURLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") mutableURLRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") } switch self { case .post(_, let parameters): return Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: parameters).0 case .update(_, _, let parameters): return Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: parameters).0 default: return mutableURLRequest } } }
應用
使用Router
相當簡單,只要在你的ApiManager
中定義一個方法:
//MARK: - Account
func getAccounts(accountRequest: AccountsRequest, completion: (accountsResponse: AccountsResponse) -> ()) -> Request {
weak var weakSelf = self
weakSelf?.errorManager.handleReachability()
store.dispatch(LoadingShowAction(type: .Normal))
return manager.request(Router.get(AccountsRouter(), accountRequest.accountId!).URLRequest)
.validate()
.responseObject {(response: Result<AccountsResponse, NSError>) in
self.handleResponse(response, completion: { (accountsResponse) in
store.dispatch(LoadingHideAction())
completion(accountsResponse: accountsResponse)
})
}
}
github:Router