使用Alamofire路由器管理不同的环境URL

时间:2020-10-27 14:20:37

标签: swift enums alamofire alamofire-request

Alamofire路由器是路由Alamofire请求的一种很好的机制。根据文档,使用以下代码很简单:

enum Router: URLRequestConvertible {
    case get, post
    
    var baseURL: URL {
        return URL(string: "https://httpbin.org")!
    }
    
    var method: HTTPMethod {
        switch self {
        case .get: return .get
        case .post: return .post
        }
    }
    
    var path: String {
        switch self {
        case .get: return "get"
        case .post: return "post"
        }
    }
    
    func asURLRequest() throws -> URLRequest {
        let url = baseURL.appendingPathComponent(path)
        var request = URLRequest(url: url)
        request.method = method
        
        return request
    }
}

在许多应用程序中,您可能具有测试URL和生产URL。是否有任何方法可以优雅地维护默认情况下无法初始化的enum

0 个答案:

没有答案