ios - 如何调试 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)
}
}
解决方案
为了开始解决此问题,您需要查看协议是什么。
关注与这种情况相关的信息,它们本质上定义了函数的签名(除其他外)。协议的名称和函数签名为给定函数的实现应该是什么留下了线索。这很容易通过一个简单的例子来说明:
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?
}
我希望这个对你有用 :)
推荐阅读
- google-app-engine - 如何知道历史上超出了哪个 appengine 配额
- angular - Angular - 为什么订阅?为什么不直接在组件中使用服务的属性?
- angular - 以角度 4 更改所选链接的颜色
- python - 无法定位元素:python 爬行中的 css 选择器或 xpath
- java - 这是对这种方法进行单元测试的好方法吗?
- spring - 无法在应用程序上下文配置文件中添加任务调度程序标签
- javascript - javascript 显示隐藏师下载内容
- python - SQLAlchemy-执行存储过程并填充类
- python-3.x - 诺依曼发电机计数
- php - 用 php 显示存储在数据库中的家谱树