iOS应用程序中更好的使用路由—Swift

2017-03-24  本文已影响280人  Supremodeamor

原文地址:https://medium.com/swift-programming/better-routing-for-ios-applications-with-router-in-swift-9b47cc8cb4c7#.9dhtbth5f

译:
在这篇文章中,我将讨论我之前在程序开发中使用的可以让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的枚举:

应用

使用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

上一篇 下一篇

猜你喜欢

热点阅读