Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) - swift

I am building an app with Swift and SwiftUI. In MainViewModel I have a function who call Api for fetching JSON from url and deserialize it. this is made under async/await protocol.
the problem is the next, I have received from xcode the next comment : "Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates." in this part of de code :
func getCountries() async throws{
countries = try await MainViewModel.countriesApi.fetchCountries() ?? []
}
who calls this one:
func fetchCountries() async throws -> [Country]? {
guard let url = URL(string: CountryUrl.countriesJSON.rawValue ) else {
print("Invalid URL")
return nil
}
let urlRequest = URLRequest(url: url)
do {
let (json, _) = try await URLSession.shared.data(for: urlRequest)
if let decodedResponse = try? JSONDecoder().decode([Country].self, from: json) {
debugPrint("return decodeResponse")
return decodedResponse
}
} catch {
debugPrint("error data")
}
return nil
}
I would like to know if somebody knows how I can fix it

First fetch the data asynchronously and then assign the result to the property on the main thread
func getCountries() async throws{
let fetchedData = try await MainViewModel.countriesApi.fetchCountries()
await MainActor.run {
countries = fetchedData ?? []
}
}
Off topic perhaps but I would change fetchCountries() to return an empty array rather than nil on an error or even better to actually throw the errors since it is declared as throwing.
Something like
func fetchCountries() async throws -> [Country] {
guard let url = URL(string: CountryUrl.countriesJSON.rawValue ) else {
return [] // or throw custom error
}
let urlRequest = URLRequest(url: url)
let (json, _) = try await URLSession.shared.data(for: urlRequest)
return try JSONDecoder().decode([Country].self, from: json)
}

There are two ways to fix this. One, you can add the #MainActor attribute to your functions - this ensures they will run on the main thread. Docs: https://developer.apple.com/documentation/swift/mainactor. However, this could cause delays and freezing as the entire block will run on the main thread. You could also set the variables using DispatchQueue.main.async{} - see this article from Hacking With Swift. Examples here:
#MainActor func getCountries() async throws{
///Set above - this will prevent the error
///This can also cause a lag
countries = try await MainViewModel.countriesApi.fetchCountries() ?? []
}
Second option:
func getCountries() async throws{
DispatchQueue.main.async{
countries = try await MainViewModel.countriesApi.fetchCountries() ?? []
}
}

Related

How to ignore async let throws error when save response in tuple?

i have a code like this:
Task {
async let configsReq = self.interactor.getConfigs()
async let optionsReq = self.interactor.getOptions()
async let updateStateReq = self.interactor.getAppUpdateState()
async let contactsReq = self.interactor.getContactOptions()
var config: Config?
var options: AvailableOptions?
var updateState: UpdateType?
var contacts: ContactOptions?
do {
config = try await configsReq
} catch {
config = nil
}
do {
options = try await optionsReq
} catch {
options = nil
}
do {
updateState = try await updateStateReq
} catch {
updateState = nil
}
do {
contacts = try await contactsReq
} catch {
contacts = nil
}
self.goToNextPage()
}
in this case it does not matter for me that the requests get correct response or throws error. i don't want to block user to get correct response.
And also I want to make sure that all my requests are answered (correct or error response) to take the user to the next page
how can i write these codes cleaner and better with new swift concurrency?
i tried like this (but i could not get match error to each related request):
Task {
async let configs = self.interactor.getConfigs()
async let options = self.interactor.getOptions()
async let updateState = self.interactor.getAppUpdateState()
async let contacts = self.interactor.getContactOptions()
do {
let array = try await [configs, options, updateState, contacts]
} catch {
print(error)
}
}
If I understand the question correctly, you want to:
“match error to each related request”, but that
you want to proceed regardless of success or failure, as it “does not matter for me that the requests get correct response or throws error”.
If that is the pattern you are looking for, I might suggest using Task result:
async let configsReq = Task { try await interactor.getConfigs() }
async let optionsReq = Task { try await interactor.getOptions() }
async let stateReq = Task { try await interactor.getAppUpdateState() }
async let contactsReq = Task { try await interactor.getContactOptions() }
let config = await configsReq.result
let options = await optionsReq.result
let state = await stateReq.result
let contacts = await contactsReq.result
goToNextPage(config: config, options: options, state: state, contacts: contacts)
Or, more concisely:
async let configs = Task { try await interactor.getConfigs() }
async let options = Task { try await interactor.getOptions() }
async let state = Task { try await interactor.getAppUpdateState() }
async let contacts = Task { try await interactor.getContactOptions() }
await goToNextPage(config: configs.result, options: options.result, state: state.result, contacts: contacts.result)
Where goToNextPage might be defined as:
func goToNextPage(
config: Result<Config, Error>,
options: Result<AvailableOptions, Error>,
state: Result<UpdateType, Error>,
contacts: Result<ContactOptions, Error>
) { … }
That way, goToNextPage can look at the .success or .failure for each, to retrieve either the value or error associated with each of the four requests.
Needless to say, you also could have four properties for these four requests, and then goToNextPage could refer to those, rather than taking them as parameters to the method. It’s functionally the same thing, but you have to decide either local vars that are passed to the next method or update properties that are accessed by the next method.
You asked:
… if we don't want to use Result anymore, how can do that?
Yes, we do not use Result very much, anymore, as that was historically a pattern for returning either value or error in traditional asynchronous patterns, and nowadays we try a series of tasks, catch thrown errors, but generally early exit once one of them fails.
But if you really want to capture the success and failure for each of the four concurrent requests, then Result encapsulates that quite well.
I would make a little helper that helps wrap the error into a Result:
extension Result {
init(asyncCatching block: () async throws -> Success) async where Failure == Error {
do {
self = .success(try await block())
} catch {
self = .failure(error)
}
}
}
In case of errors, you even get the Error object for each getXXX method, rather than just a nil. Of course, if you really just want a nil, you can write a helper that returns optionals instead.
// this is essentially like refactoring out the repeated parts of your first code
func asyncCatchWithNil<Result>(function: () async throws -> Result) async -> Result? {
do {
return try await function()
} catch {
return nil
}
}
Then you could do:
Task {
async let configs = Result(asyncCatching: self.interactor.getConfigs)
async let options = Result(asyncCatching: self.interactor.getOptions)
async let updateState = Result(asyncCatching: self.interactor.getAppUpdateState)
async let contacts = Result(asyncCatching: self.interactor.getContactOptions)
/* or
async let configs = asyncCatchWithNil(function: self.interactor.getConfigs)
async let options = asyncCatchWithNil(function: self.interactor.getOptions)
async let updateState = asyncCatchWithNil(function: self.interactor.getAppUpdateState)
async let contacts = asyncCatchWithNil(function: self.interactor.getContactOptions)
*/
let (configsResult, optionsResult, updateStateResult, contactsResult)
= await (configs, options, updateState, contacts)
// you can inspect each result here if you'd like
self.goToNextPage()
}
The idea here is that you get a type that can contain both the response and error at the point of async let, rather than catching the error later.

Is there any way to implement a taskGroup to run in parrarel inside another taskGroup?

I am using Firebase to fetch some data from it with a Continuation. Before resuming the continuation I want to run a group of async tasks inside(fetch other data). This would let me achieve maximum concurrency.
I have tried two methods to do this, both does not work.
This is what I have tried first trying to use inside a continuation a taskGroup.(Code Below). The error is in comment.
First Option
try? await withThrowingTaskGroup(of: Void.self) { group in
for referencePosts in referencePostsDict.keys {
group.addTask {
return try! await self.fetchPost(reference: referencePosts)
}
}
func fetchPost(reference: String) async throws -> Void{
var db_ref = Database.database(url:FIREBASEURL.url)
.reference()
.child("posts")
.child(reference)
typealias postContinuation = CheckedContinuation<Void,Error>
return try await withCheckedThrowingContinuation{
(continuation : postContinuation) in
db_ref.observeSingleEvent(of: .value) { data in
if data.exists(){
var three = data.value as! [String : Any]
withThrowingTaskGroup(of: Void.self) { group in //async' call in a function that does not support concurrency
(three["picturePaths"] as! [String : String]).forEach { key, value in
if key != "O"{
group.addTask {
try? await self.fetchPictureDataL(picRef: key)
}
self.threePictures[key] = value
}
}
}
self.threePosts[reference] = three
continuation.resume(returning: ())
}else{
continuation.resume(returning: ())
}
}
}
}
func fetchPictureDataL(picRef : String) async throws ->Void{
var db =Database
.database(url:FIREBASEURL.url)
.reference()
.child("pictures").child(picRef)
typealias postContinuation = CheckedContinuation<Void,Error>
return try await withCheckedThrowingContinuation{
(continuation : postContinuation) in
db.observeSingleEvent(of: .value) { data in
self.threePicturesFetched[picRef] = three as! [String : Any]
continuation.resume(returning: ())
}
}
}
I commented the code where the compiler reports a problem.
Second Option
fetchCheckIn2 method is modified to return a [String]
This is the second method where I have tried to achieve the same result different, to mention the fetchCheckIn2 method is modified to return a [String].
What I want to achieve is that the fetchPictureDataL will run in parallel inside a Task or group, and will not run awaiting each other to finish.
//fetching all references
try! await withThrowingTaskGroup(of: [String].self) { firstGroup in
for referenceCheckIn in reference_checkInInt_dictionary.keys {
firstGroup.addTask {
return try await self.fetchCheckIn2(reference: referenceCheckIn)
}
}
for try await pictureArray in firstGroup {
if pictureArray.count != 0 {
for pic in pictureArray {
try! await self.fetchPictureDataL(picRef: pic)
}
}
}
}
Trying to achieve
I want to achieve parallelism even with fetchPictureDataL method?
If not clear why I am trying to do this, please read the use of case.
Use of this case:
I have social media app with posts. I have a list of paths in order to fetch the post. Each post contains an array of other paths which are pictures.
I want to fetch posts parrarel and also fetch the pictures in parrarel, in a taskGruop, so all this fetch of post+picture is awaited and can be displayed to User.
Thank you

Swift async method call for a command line app

I'm trying to reuse some async marked code that works great in a SwiftUI application in a simple Swift-Command line tool.
Lets assume for simplicity that I'd like to reuse a function
func fetchData(base : String) async throws -> SomeDate
{
let request = createURLRequest(forBase: base)
let (data, response) = try await URLSession.shared.data(for: request)
guard (response as? HTTPURLResponse)?.statusCode == 200 else {
throw FetchError.urlResponse
}
let returnData = try! JSONDecoder().decode(SomeData.self, from: data)
return returnData
}
in my command line application.
A call like
let allInfo = try clerk.fetchData("base")
in my "main-function" gives the error message 'async' call in a function that does not support concurrency.
What is the correct way to handle this case.
Thanks
Patrick
To call an async method the call must take place inside an async method or wrapped in a Task.
Further the method must be called wirh await
Task {
do {
let allInfo = try await clerk.fetchData("base")
} catch {
print(error)
}
}
You can make the entry point of the CLI async with this syntax
#main
struct CLI {
static func main() async throws {
let args = CommandLine.arguments
...
}
The name of the struct is arbitrary.
If you are using Argument Parser framework then from version 1.0 it supports async context. You have to make your struct conforms to protocol AsyncParsableCommand. It creates context in which async function can be run safely.

How to Return HTTP Request Data in a Function Call in Swift?

I want to make a generic HTTP request function. The code I saw does not return data to the caller. Instead it prints out the error code or the parsed JSON object within the function. In my case I would like to return (data, response, error) to the caller.
func performHTTPRequest(urlString: String) -> (Data, URLResponse, Error) {
if let url = URL(string: urlString) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) {(data, response, error) in
// some logic
}
task.resume()
}
}
The problem is the three variables (data, response, error) are not available outside the closure. If I assign them to global variables within the closure, compiler complains the global variables are not in scope.
Also, where would I put the return (data, response, error) statement? Before or after task.resume()? Thanks
The short answer is, you can't. You can us the new async/await syntax in Swift 5.5 to simulate a synchronous network call. (I haven't had a chance to use async/await in my own projects yet, so I'd have to look that up in order to guide you.)
Without async/await, you will need to refactor your function to take a completion handler. You'd then call the completion handler with the results once the data task completes.
This question comes up all the time on SO. You should be able to find dozens of examples of writing a completion handler-based function for async networking.
For example you can do that
struct Message: Decodable {
var username: String
var message: String
}
enum RequestError: Error {
case invalidURL
case missingData
}
func performHTTPRequest(urlString: String) async throws -> Message{
guard let url = URL(string: urlString) else {throw RequestError.invalidURL}
guard let (data, response) = try? await URLSession.shared.data(from: url) else{throw RequestError.invalidURL}
guard (response as? HTTPURLResponse)?.statusCode == 200 else {throw RequestError.invalidURL}
let decoder = JSONDecoder()
guard let jsonResponse = try? decoder.decode(Message.self, from: data) else {throw RequestError.missingData}
return jsonResponse
}
and call the fonction
do {
try await performHTTPRequest(urlString: "wwww.url.com")
} catch RequestError.invalidURL{
print("invalid URL")
} catch RequestError.missingData{
print("missing data")
}

How to refactor Swift API call to use Swift 5.5 async/await?

I want to refactor some API calls to use Swift 5.5's new async/await in my SwiftUI project. However, it's unclear to me how to replace or accomodate the completions.
Here's an example function which I want to refactor:
static func getBooks(completion: #escaping ([Book]?) -> Void) {
let request = getRequest(suffix: "books")
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
fatalError("Error: \(error)")
}
if let data = data {
if let books = try? JSONDecoder().decode([Book].self, from: data) {
DispatchQueue.main.async {
print("books.count: \(books.count)")
completion(books)
}
return
} else {
fatalError("Unable to decode JSON")
}
} else {
fatalError("Data is nil")
}
}.resume()
}
I beleve the new function signature would look something like this:
static func getBooks() async throws -> ([Book]?) {
// ...
}
However, I have no idea what to do with the URLSession.shared.dataTask, DispatchQueue.main.async and completion, etc.
Anyone know what the new function body should look like?
Thanks
func getBooks() async throws -> [Book] {
let (data, _) = try await URLSession.shared.data(for: request)
return try JSONDecoder().decode([Book].self, from: data)
}
This will throw if the request fails, and if the response cannot be decoded. Since the function is marked as throwing, then the calling function has to handle the raised errors.
You don't need to declare the returned [Book] to be optional, because it will either return an honest array, or throw an error.
In your additional code, you had to call your completion handler on the main queue, because you were calling it from within the completion block of the request. You don't need to do that here.