为了开始解决此问题,您需要查看协议是什么。
关注与这种情况相关的信息,它们本质上定义了函数的签名(除其他外)。协议的名称和函数签名为给定函数的实现应该是什么留下了线索。这很容易通过一个简单的例子来说明:
protocol MathematicalOperations {
func add(_ int: Int, to int: Int) -> Int
}
class Calculator: MathematicalOperations {
func add(_ intA: Int, and intB: Int) -> Int {
return intA + intB
}
}
// Usage
let calculator = Calculator()
let sum = calculator.add(15, and: 10)
print(sum) // 25
将其与您的情况联系起来。该协议APIService
已定义如下功能:
protocol APIService {
func JSONTaskWithRequest(request: URLRequest, completion: (JSON?, HTTPURLResponse?, NSError?) -> Void) -> JSONTask
init(config: URLSessionConfiguration)
}
你的EventAPIClient
类告诉编译器它意味着遵守APIService
协议:
final class EventAPIClient: APIService {
为了符合协议,EventAPIClient
需要为APIService
.
至于解决问题,缺少一些关于 JSONTask 定义等的信息。但是,这是一个示例实现,如果没有别的,应该给你一个起点:
func JSONTaskWithRequest(request: URLRequest, completion: @escaping (JSON?, HTTPURLResponse?, NSError?) -> Void) -> JSONTask {
let task = session.dataTask(with: request) { data, response, error in
if let error = error {
completion(nil, response, error as NSError?)
} else if HTTPResponse.statusCode == 200 { // OK response code
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? JSON
completion(json, response, nil)
} catch let error as NSError {
completion(nil, response, error)
}
} else {
completion(nil, response, nil) // could create an error saying you were unable to parse JSON here
}
}
return task as? JSONTask
}
init(config: URLSessionConfiguration) {
self.configuration = config
self.token = "APIKey" // put your default api key here, maybe from a constants file?
}
我希望这个对你有用 :)