HomeiOS Developmentios - Returning knowledge from async name in Swift perform

ios – Returning knowledge from async name in Swift perform


Launched in Swift 5.5 (iOS 15, macOS 12), we might now use the asyncawait sample:

func fetchGenres() async throws -> [Genre] {
    …
    let (knowledge, _) = strive await URLSession.shared.dataTask(for: request)
    return strive JSONDecoder().decode([Genre].self, from: knowledge)
}

And we might name it like:

let genres = strive await fetchGenres()

The asyncawait syntax is much extra concise and pure than the normal completion handler sample outlined in my authentic reply, beneath.

For extra data, see Meet async/await in Swift.


The historic sample is to make use of completion handlers closure.

For instance, we might usually use Consequence:

func fetchGenres(completion: @escaping (Consequence<[Genre], Error>) -> Void) {
    ...
    URLSession.shared.dataTask(with: request) { knowledge, _, error in 
        if let error = error {
            DispatchQueue.foremost.async {
                completion(.failure(error))
            }
            return
        }

        // parse response right here

        let outcomes = ...
        DispatchQueue.foremost.async {
            completion(.success(outcomes))
        }
    }.resume()
}

And also you’d name it like so:

fetchGenres { leads to
    change outcomes {
    case .failure(let error):
        print(error.localizedDescription)

    case .success(let genres):
        // use `genres` right here, e.g. replace mannequin and UI            
    }
}

// however don’t attempt to use `genres` right here, because the above runs asynchronously

Notice, above I’m dispatching the completion handler again to the primary queue to simplify mannequin and UI updates. Some builders take exception to this follow and both use no matter queue URLSession used or use their very own queue (requiring the caller to manually synchronize the outcomes themselves).

However that’s not materials right here. The important thing concern is using completion handler to specify the block of code to be run when the asynchronous request is completed.


Notice, above I retired using NSArray (we don’t use these bridged Goal-C varieties any extra). I assume that we had a Style sort and we presumably used JSONDecoder, reasonably than JSONSerialization, to decode it. However this query didn’t have sufficient details about the underlying JSON to get into the main points right here, so I omitted that to keep away from clouding the core concern, using closures as completion handlers.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments