GoldenDragon 1.0.0

GoldenDragon 1.0.0

Harsh Vishwakarma 保持。



  • 作者:
  • harsh

GoldenDragon

iOS 网络框架

Image of Yaktocat

如何使用?

  • 扩展 EndPointType 协议
  • 为进行网络调用重新实现 Router
  • 使用 Codable 协议
enum Api {
    case search(query: String)
}

extension Api: EndPointType {
    
    public  var host: String {
        return "api.github.com"
    }
    
    public  var scheme: String {
        return "https"
    }
    
    public  var path: String {
        switch self {
        case .search:
            return "/search/repositories"
        }
    }
    
    public var httpMethod: HTTPMethod {
        switch self {
        case .search:
            return .get
        }
    }
    
    public var task: HTTPTask {
        switch self {
        case .search(let query):
            let params: Parameters = [
                "q": query
            ]
            return .requestParameters(bodyParameters: nil, bodyEncoding: .urlEncoding, urlParameters: params)
        }
    }
    
    public var headers: HTTPHeaders? {
        return nil
    }
}
 private var router: Router<Api> = Router<Api>()
 
 func testApi() {
        
        let expect: Future<SearchResult> = router.request(Api.search(query: "swift"))
        expect.observe { result in
            switch result {
            case .success(let searchData):
                print("\(searchData.totalCount) repositories found")
            case .failure(let error):
                print(error.localizedDescription)
            }
        }        
    }
 struct SearchResult: Codable {
        let totalCount: Int
        let items: [Item]
        
        enum CodingKeys: String, CodingKey {
            case totalCount = "total_count"
            case items
        }
    }
    
    struct Item: Codable {
        let id: Int
        let htmlURL: String
        let description: String
        
        enum CodingKeys: String, CodingKey {
            case id
            case htmlURL = "html_url"
            case description
        }
    }