popeyelau / wiki

📒Wiki for many useful notes, source, commands and snippets.
2 stars 0 forks source link

基于 Alamofire 实现简单路由 #5

Open popeyelau opened 5 years ago

popeyelau commented 5 years ago
import Alamofire

protocol APIConfiguration: URLRequestConvertible {
    var method: HTTPMethod { get }
    var path: String { get }
    var parameters: Parameters? { get }
}

enum Router: APIConfiguration {
    case topics
    case search(keywords: String, page: Int)
    case resource(id: String)

    var method: HTTPMethod {
        return .get
    }

    var path: String {
        switch self {
        case .topics:
            return "/topics"
        case .search:
            return "/search"
        case .resource(let id):
            return "/resource/\(id)"
        }
    }

    var parameters: Parameters? {
        switch self {
        case .search(let keywords, let page):
            return ["wd": keywords, "p": page]
        default:
            return nil
        }

    }

    var encoding: ParameterEncoding {
        return URLEncoding.default
    }

    func asURLRequest() throws -> URLRequest {
        let url = try ENV.host.asURL()
        var request = URLRequest(url: url.appendingPathComponent(path))

        request.httpMethod = method.rawValue
        return try encoding.encode(request, with: parameters)
    }
}
//使用
 Alamofire.request(Router.topics)...

参考资料 Write a Networking Layer in Swift 4 using Alamofire 5 and Codable Part 1: API Router