With the following code im am trying to organise server calls synchronously:
func synchronousGetRequest(group: DispatchGroup, completion: @escaping ()-> ()) {
guard var url = URL(string: "https://192.168.187.30:5001/") else {return}
let session = URLSession.shared.dataTask(with: url) { _, _, _ in
completion()
}
session.resume()
group.wait()
}
func loopFunc() {
let group = DispatchGroup()
for _ in 1...5 {
print("start request")
group.enter()
synchronousGetRequest(group: group) {
print("request finished\n")
group.leave()
}
}
}
DispatchQueue.global(qos: .background).async {
loopFunc()
}
print("End of script")
But im not much familiar with threading on Swift and I know that blocking threads might not be a good practice. Is it safe to run this function in a production application as long it's placed on a background thread?
Output:
End of script
start request
request finished
start request
request finished
start request
request finished
start request
request finished
start request
request finished
Thanks in advance!