jsonswiftgenericsalamofirepromisekit

Issue To Create A Base Service <Alamofire,PromiseKit,Generic>


Hello everyone I want to crate a base api service for my apps but when I try a lot of different way but i can't solve my problems. I have to use alamofire, promiseKit and generic's.

My first solution and his issue: I can get my json from api but when I try to decode my json every time it fails. There is the code:

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)
            }
        }
    }

}

My second solution and issue : When I do my request I get my json response and decode it but in this solution I can't return data with seal.fulfill(data) gives me "Cannot convert value of type 'Any' to expected argument type 'T'" and when I try to seal.fulfill(data as! T) like this when I run app always crashes. There is my code :

    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)
            }
        }
    }
}

Finally I'm using test api https://www.flickr.com/services/api/explore/flickr.photos.getRecent to test my code. How I can solved this issue's ? Thanks for your helps


Solution

  • Use responseDecodable instead of responseString or responseJSON.

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