The below URLRequest is freezing my UI until it completes. I tried implementing this answer by adding DispatchQueue.main.async {}
. I also tried adding DispatchQueue.global(qos: .background).async {)
on the function itself, with no results. I’d really appreciate if my UI does not get blocked while the request takes place.
DispatchQueue.global(qos: .background).async {
uploadString()
}
func uploadString() {
// Create a URLRequest for an API endpoint
guard let url = URL(string: "http://111.111.11.111:5000/upload") else {
print("Invalid URL")
return
}
var request = URLRequest(url: url)
// Change the URLRequest to a POST request
request.httpMethod = "POST"
request.setValue("text/plain", forHTTPHeaderField: "Content-Type")
request.httpBody = "test"
// Create the HTTP request
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
if let error = error {
// Handle HTTP request error
DispatchQueue.main.async {
print("Error: (error.localizedDescription)")
}
} else if let data = data {
// Handle HTTP request response
if let responseString = String(data: data, encoding: .utf8) {
DispatchQueue.main.async {
print("Response from server: (responseString)")
}
} else {
DispatchQueue.main.async {
print("Failed to convert data to string")
}
}
} else {
DispatchQueue.main.async {
print("Unexpected error")
}
}
}
task.resume()
}
2