ios - UIApplication applicationState 只能在主线程中使用
问题描述
我正在尝试对 API 进行一些单元测试。这是实际的功能。
func registerApi(path: String, player_id: Int, contest_id: Int, country_id: Int, success: () -> Void)
{
ServiceHelper.sharedInstance.sendRequest(path: "register-country",
params: ["api_token": Constants.USER_INFO["api_token"].rawValue,
"player_id": player_id,
"country_id": country_id,
"contest_id": contest_id],
showSpinner: true,
completionHandler:
{ (response, error) in
if (error != nil)
{
Test to be failed
}
else
{
Test Passed
}
})
}
而且,现在这里是单元测试的测试功能。
func testApiWorking()
{
let controller = WorldCupChooseCountryVC()
let expected = XCTestExpectation(description: "Some Countries to return")
controller.registerApi(path: "get-country", player_id: 163, contest_id: 1, country_id: 1) { success in if success { expected.fulfill() }
else{
XCTFail()
}
}
waitForExpectations(timeout: 1.0) { (_) -> Void in
}
}
但是,每当我尝试对此进行测试时,都会出现以下错误。
[UIApplication applicationState] must be used from main thread only
有一次,它也跑得很好,测试失败了,但它跑了。但是,它现在甚至没有运行。
解决方案
主线程检查器从后台线程检测 AppKit、UIKit 和其他 API 的无效使用。completionHandler
似乎更新了 UI,因此可能将该部分移至单独的方法并使用 Dispatch Queue 调用它。
DispatchQueue.main.async {
handleResponseOrError(response, error)
}
推荐阅读
- python - 如何识别lstm模型中的节点和层数
- linux - 如何从bash脚本将数组传递给ansible额外变量
- r - 如何从日期时间中提取小时(UTC 时间)
- python - 在 groupby 中查找 pandas 数据框索引的交集
- azure-ad-b2c - Azure Active Directory B2C 身份:身份验证和校对
- airflow - 触发规则 ONE_FAILED 满足时气流任务未触发
- ios - 打开“com.XX.XX”的请求失败请求仅在使用排毒时被服务委托拒绝
- html - Bootstrap 4 justify-space-around 和 justify-content-center 没有对齐
- postgresql - postgresql docker 复制
- node.js - 为什么强大的“多重”选择不适用于“多部分/表单数据”?