test()
在让方法运行之前,我需要执行多个调用。我有一个完成块,我正在使用waitForExpectations()
. 由于有不止一个异步调用,我使用了一个计数器。我expectation.fulfill()
只在计数器达到调用次数时才让这种情况发生。
override func setUp() {
super.setUp()
let exp = expectation(description: "waitForSetUp")
var counter = 0
// Issue an async request
self.addEventToCalendar(title: "Test1", description: "Description test1", startDate: NSDate().addingTimeInterval(-36000), endDate: NSDate()){(success, error) in
if (success) && (error == nil) {
counter = counter + 1
if(counter == 2){exp.fulfill()}
}
}
self.addEventToCalendar(title: "Test2", description: "Description test2", startDate: NSDate(), endDate: NSDate().addingTimeInterval(36000)){(success, error) in
if (success) && (error == nil) {
counter = counter + 1
if(counter == 2){exp.fulfill()}
}
}
waitForExpectations(timeout: 40, handler: nil)
}
这种结构不起作用。该test()
方法有时会在调用返回之前运行(并非总是如此)。
如何setUp()
等待返回多个异步调用?