Get result from async closure - Unexpected found nil while unwrapping an Optional value

72 Views Asked by At

I am using Cycle library to access to my web service. This is the function I use for POST method:

func register(requestObj: AnyObject, completion: (result: Int) -> ()){
        Cycle.post("someURL",
            requestObject: requestObj,
            requestProcessors: [JSONProcessor()],
            completionHandler: {(cycle, error) in
                var status = cycle.response.statusCode!
                completion(result: status)
        })
}

As you can see, I tried to pass the callback to get the status code. I tried to get the result in the below test function:

func test_RegRequest_UT002(){
        var obj = ["email" : "[email protected]", "password" : "Test@123", "confirmpassword" : "Test@123"]

        UserService.register(obj){ result in //Unexpected found nil while unwrapping an Optional value
            println("This is the response code: \(result)")
        }
}

I got it right when I first try function register in test with the help of expectationWithDescription. I guess the error above occurs when the test code trying to get the value but the closure has not received the response from server yet.

Please suggest me what should I do next in this situation? It is good if there is something can make the main thread wait until receiving response from web service.

0

There are 0 best solutions below