Home > Net >  Safe synchronous server requests with Swift
Safe synchronous server requests with Swift

Time:09-16

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!

CodePudding user response:

Your approach is fine but a better way is async/await.

The loop is executed in order although the requests are asynchronous.

func synchronousGetRequest() async throws -> String  {
    let url = URL(string: "https://192.168.187.30:5001/")!
    for i in 1...5 {
        print("start request \(i)")
        let (_, _) = try await URLSession.shared.data(from: url)
        print("end request \(i)")
        
    }
    return "End of script"
}

Task.detached {
    do {
        let result = try await synchronousGetRequest()
        print(result)
    } catch {
        print(error)
    }
}

Output:

start request 1
end request 1
start request 2
end request 2
start request 3
end request 3
start request 4
end request 4
start request 5
end request 5
End of script
  • Related