我正在使用REST进行大量调用,并决定将这些连接调用分离为一个单独的对象,从我的UI类中调用。这是我正在使用的功能,它不会等待请求完成。我不确定我做错了什么,并尝试使用堆栈和网络中的许多示例,包括:
Wait until swift for loop with asynchronous network requests finishes executing
Waiting until the task finishes
//let loader = from Oauth2/p2_OAuth2 pod to load JSON
func ConnectionHandler()
{
let dg = DispatchGroup()
switch self.RequestType
{
case aRequest:
//if I make a single call here, works fine
case bRequest:
//if I make a single call here, works fine
case abRequest:
//when making requests for both type a and b, can’t get it to work
dg.enter()
loader.perform(request: self.userDataRequest)
{ response in
do
{
let json = try response.responseJSON()
self.structWrapper.aArray = self.loadAArray(dict: json)
}
catch let error {
self.didCancelOrFail(error)
}
}
self.dexRequestType = DexRequestTypesEnum.glucoseValues
//ignore last line. should be removed.
loader.perform(request: self.userDataRequest)
{ response in
do
{
let json = try response.responseJSON()
self.structWrapper.bArray = self.loadBArray(dict: json) }
catch let error {
self.didCancelOrFail(error)
}
}
dg.leave()
dg.notify(queue: .main)
{
//will print, but requests are not complete, arrays are empty, even though breakpoints hit in loading them.
for x in self.structWrapper.aArray
{
print(x.displayTime + ":" + x.units)
}
for y in self.structWrapper.bArray
{
print(y.displayTime + ":" + String(y.someNumber)
}
print(“tasks complete”)
}
}
}
答案 0 :(得分:3)
你必须使用
在调用Task 之前dg.enter() 任务完成后
dg.leave()
就像那样:
return function() {
localVar++;
return localVar;
}