I'm trying to get data from the network request using PromiseKit in the following code below, but on the line seal.fulfill(data)
I'm getting the error 'Cannot invoke 'fulfill' with an argument list of type '(Data)''. Can anyone please give me a hint on what am I doing wrong?
import Foundation
import PromiseKit
class NetworkService {
let baseHost: String = "api.someAwesomeSite.com"
var version: String { return "3.345" }
let configuration = URLSessionConfiguration.default
func getData<Data>(method: String, queryItems: [URLQueryItem] = []) -> Promise<Data> {
var urlConstructor = URLComponents()
urlConstructor.scheme = "https"
urlConstructor.host = self.baseHost
urlConstructor.path = "/method/\(method)"
urlConstructor.queryItems = [
URLQueryItem(name: "user_id", value: ApiManager.session.userId),
URLQueryItem(name: "access_token", value: ApiManager.session.token),
URLQueryItem(name: "v", value: version),
]
urlConstructor.queryItems?.append(contentsOf: queryItems)
let request = URLRequest(url: urlConstructor.url!)
let session = URLSession(configuration: configuration)
return Promise<Data> { seal in
let task = session.dataTask(with: request) { (data, response, apiError) in
if let error = apiError {
seal.reject(error)
}
if let data = data {
seal.fulfill(data)
}
}
task.resume()
}
}
I think you're just a little confused with your generic arguments. Change:
func getData<Data>(method: String, queryItems: [URLQueryItem] = []) -> Promise<Data> {
to
func getData(method: String, queryItems: [URLQueryItem] = []) -> Promise<Data> {
The problem was that when you have Data
as a generic type argument, the compiler is thinks Data
is some type you will define... but within the function you are also using Data
to refer to the Swift library Data
type and it can't be both things at the same time.