【问题标题】:Issue To Create A Base Service <Alamofire,PromiseKit,Generic>创建基础服务的问题 <Alamofire,PromiseKit,Generic>
【发布时间】:2020-04-23 10:08:27
【问题描述】:

大家好,我想为我的应用程序创建一个基本的 api 服务,但是当我尝试了很多不同的方式时,我无法解决我的问题。我必须使用 alamofire、promiseKit 和 generic's。

我的第一个解决方案和他的问题:我可以从 api 获取我的 json,但是当我每次尝试解码我​​的 json 失败时。有代码:

func fetchData<T: Codable>(_ page: Int) -> Promise<T> {

    let path = getPath(page)

    return Promise<T> { seal in
        AF.request(path, method: .get).validate(statusCode: 200..<300).responseString { response in
            switch response.result {
            case .success(let data):
                if let json = data.data(using: .utf8) {
                    do {
                        let res = try JSONDecoder().decode(T.self, from: json)
                        print(res)
                        seal.fulfill(res)
                    } catch {
                        print("json serilaztion error")
                        print(error)
                        seal.reject(error)
                    }
                }
            case .failure(let error):
                seal.reject(error)
            }
        }
    }

}

我的第二个解决方案和问题:当我提出请求时,我得到我的 json 响应并对其进行解码,但在此解决方案中,我无法使用 seal.fulfill(data) 返回数据给我“无法转换‘任何’类型的值到预期的参数类型 'T'" 并且当我尝试像这样运行应用程序时像这样 seal.fulfill(data as!T) 总是崩溃。有我的代码:

    func fetchData<T: Codable>(_ page: Int) -> Promise<T> {

    let path = getPath(page)

    return Promise<T> { seal in
        AF.request(path, method: .get).validate(statusCode: 200..<300).responseJSON { response in
            switch response.result {
            case .success(let data):
                seal.fulfill(data as! T) // Cannot convert value of type 'Any' to expected argument type 'T'
            case .failure(let error):
                seal.reject(error)
            }
        }
    }
}

最后我正在使用测试 api https://www.flickr.com/services/api/explore/flickr.photos.getRecent 来测试我的代码。我该如何解决这个问题?感谢您的帮助

【问题讨论】:

    标签: json swift generics alamofire promisekit


    【解决方案1】:

    使用responseDecodable 代替responseStringresponseJSON

    AF.request(...).responseDecodable(of: T.self) { response in
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-27
      • 2018-12-05
      • 1970-01-01
      • 2014-06-16
      • 2014-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多