UIApplication applicationState 只能在主线程中使用

UIApplication applicationState must be used from main thread only

我正在尝试为 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

曾经,它也运行好吧,测试失败了,但是它运行。但是,现在连运行都不到了。

Main Thread Checker 从后台线程检测 AppKit、UIKit 和其他 API 的无效使用。 completionHandler似乎要更新 UI 所以可能将该部分移到一个单独的方法中并使用 Dispatch Queue 调用它。

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

(Question changed from being about the main thread to how to define and call closures. This answer has changed to reflect that.)

[UIApplication applicationState] is most likely being called from within the GeneralHelper.

The service helper is most likely making the network request on a background thread.

So, to make sure GeneralHelper is called on the main thread, execute it via a DispatchQueue.

(另外!您没有调用完成处理程序,所以我们也会添加它。)

func registerApi(path: String, player_id: Int, contest_id: Int, country_id: Int,  completion: ((Bool) -> Void)? = nil)
{
    let helper = ServiceHelper.sharedInstance
    let params = [
        "api_token": Constants.USER_INFO["api_token"].rawValue,
        "player_id": player_id,
        "country_id": country_id,
        "contest_id": contest_id
    ]
    helper.sendRequest(path: "register-country", params: params, showSpinner: true) { (response, error) in
        var success = true

        if let error = error
        {
            // Do stuff on failure.
            success = false
        }
        else
        {
            // Do stuff on success
        }

        // Call completion handler from 'registerApi'
        completion?(success)
    })
}

在您的测试中,您现在可以添加一个参数来测试是否成功。

func testApiWorking()
{
    let controller = WorldCupChooseCountryVC()

    let expected = XCTestExpectation(description: "Some Countries to return")

    controller.registerApi(path: "register-country", player_id: 163, contest_id: 1, country_id: 1) { success in
        if success {
            // Test success
        } else {
            // Test fail
        }

        expected.fulfill()
    }

    waitForExpectations(timeout: 30) { (_) -> Void in
    }
}