首页 > 解决方案 > 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

有一次,它也跑得很好,测试失败了,但它跑了。但是,它现在甚至没有运行。

标签: iosswiftuikituiapplication

解决方案


主线程检查器从后台线程检测 AppKit、UIKit 和其他 API 的无效使用。completionHandler似乎更新了 UI,因此可能将该部分移至单独的方法并使用 Dispatch Queue 调用它。

DispatchQueue.main.async {
     handleResponseOrError(response, error)
}

推荐阅读