首页 > 解决方案 > 如何调试 APIService 的代码

问题描述

我是使用 API 快速创建登录的新手。我遵循了树屋的视频教程,但我使用了不同版本的 Xcode 和 swift。我不知道我会在这些代码中添加什么。希望你能帮助我或者你能给我任何参考,我可以在创建一个登录页面时使用,该页面将在文本字段中输入密码并提交以验证代码是否存在并发布数据。太感谢了。图像中的错误

当我点击修复这些代码行出现

final class EventAPIClient: APIService {
func JSONTaskWithRequest(request: URLRequest, completion: (JSON?, HTTPURLResponse?, NSError?) -> Void) -> JSONTask {
    <#code#>
}

init(config: URLSessionConfiguration) {
    <#code#>
}


let  configuration: URLSessionConfiguration
lazy var session: URLSession = {
return URLSession(configuration: self.configuration)
}()

private let token: String

init(config: URLSessionConfiguration, APIKey: String) {
    self.configuration = config
    self.token = APIKey
}

convenience init(APIKey: String) {

    self.init(config: URLSessionConfiguration.default, APIKey: APIKey)
}
}

标签: iosswiftpasscode

解决方案


为了开始解决此问题,您需要查看协议是什么。

关注与这种情况相关的信息,它们本质上定义了函数的签名(除其他外)。协议的名称和函数签名为给定函数的实现应该是什么留下了线索。这很容易通过一个简单的例子来说明:

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

我希望这个对你有用 :)


推荐阅读