With Swift 3, using GCD has changed to DispatchGroup()
, and I'm trying to learn to use it in my code.
Currently I have a function in another class that attempts to download a file and output its speed. I like to have that function finish first because I assign its speed to a var
that I will be using in the first class to perform other tasks that is dependent upon that var
.
It goes something like this:
Second class:
func checkSpeed()
{
// call other functions and perform task to download file from link
// print out speed of download
nMbps = speedOfDownload
}
First Class:
let myGroup = DispatchGroup()
let check: SecondClass = SecondClass()
myGroup.enter()
check.checkSpeed()
myGroup.leave()
myGroup.notify(queue: DispatchQueue.main, execute: {
print("Finished all requests.")
print("speed = \(check.nMbps)")
})
The problem is Finish all requests
gets output first, thus returning nil
for speed
, then afterwards checkSpeed
finishes and outputs the correct download speed.
I believe I'm doing this wrong, but I'm not sure?
How can I ensure that speed
obtains the correct value after the completion of checkSpeed
in my first class?
The details of checkSpeed
is exactly the same as connectedToNetwork
from GitHub: connectedness.swift