ios – Returning information from async name in Swift perform

[ad_1]

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

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

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 unique reply, under.

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


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

For instance, we’d typically use Outcome:

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

        // parse response right here

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

And also you’d name it like so:

fetchGenres { ends in
    swap 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

Observe, above I’m dispatching the completion handler again to the principle queue to simplify mannequin and UI updates. Some builders take exception to this observe 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 difficulty is using completion handler to specify the block of code to be run when the asynchronous request is completed.


Observe, 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, slightly 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 difficulty, using closures as completion handlers.

[ad_2]

Leave a Reply