SwiftUI Running Async Code Within Synchronous Handler - swift

I am creating a game where, after a user signs in, I want to send their playerID to my backend. Since this is in SwiftUI, I have the following (btw I know we're not supposed to be using playerID anymore but this is just a minimal reproducible example):
import SwiftUI
import GameKit
struct SampleView: View {
let localPlayer = GKLocalPlayer.local
func authenticateUser() async {
localPlayer.authenticateHandler = { vc, error in
guard error == nil else {
print(error?.localizedDescription ?? "")
return
}
if localPlayer.isAuthenticated {
let playerID = localPlayer.playerID
GKAccessPoint.shared.isActive = localPlayer.isAuthenticated
// here is where I would like to make an async call
}
}
}
var body: some View {
VStack {
Text("Sample View")
}
.task {
await authenticateUser()
}
}
}
struct SampleView_Previews: PreviewProvider {
static var previews: some View {
SampleView()
}
}
In the comment indicating where I'd like to place an async call, I have tried something like
await myBackendCall(playerID)
but this throws the error
Invalid conversion from 'async' function of type '(UIViewController?, (any Error)?) async -> Void' to synchronous function type '(UIViewController?, (any Error)?) -> Void'
which makes sense given that the authenticateHandler function isn't an async function.
What is the best approach here? I'd like to wait until I have the value for PlayerID, and then call await myBackendCall(playerID). Any advice here would be much appreciated, thank you!

To make a completion handler async use a continuation, it returns true if the user is authenticated, otherwise false.
func authenticateUser() async -> Bool {
return await withCheckedContinuation { continuation in
localPlayer.authenticateHandler = { vc, error in
if let error {
print(error.localizedDescription)
continuation.resume(returning: false)
} else {
continuation.resume(returning: localPlayer.isAuthenticated)
}
}
}
}
and in the task scope write
.task {
let isAuthenticated = await authenticateUser()
if isAuthenticated {
let playerID = localPlayer.playerID
GKAccessPoint.shared.isActive = localPlayer.isAuthenticated
// here is where I would like to make an async call
}
}

When you have a callback closure (like authenticateHandler), it invariably means that the closure may possibly be called multiple times. The appropriate async-await pattern would be an AsyncSequence (e.g., an AsyncStream or an AsyncThrowingStream).
So, you might wrap authenticateHandler in an asynchronous sequence, like so:
func viewControllers() -> AsyncThrowingStream<UIViewController, Error> {
AsyncThrowingStream<UIViewController, Error> { continuation in
GKLocalPlayer.local.authenticateHandler = { viewController, error in
if let viewController {
continuation.yield(viewController)
} else {
continuation.finish(throwing: error ?? GKError(.unknown))
}
}
}
}
Then you could do things like:
.task {
do {
for try await _ in viewControllers() {
GKAccessPoint.shared.isActive = GKLocalPlayer.local.isAuthenticated
// do your subsequent `async` call here
}
} catch {
GKAccessPoint.shared.isActive = false
print(error.localizedDescription)
}
}
For more information, see WWDC 2021 video Meet AsyncSequence. But the idea is that withCheckedContinuation (or withThrowingCheckedContinuation) is designed for completion handler patterns, where it must be called once, and only once. If you use a checked continuation and the closure is called again, it will be “logging correctness violations”, because “You must call a resume method exactly once on every execution path throughout the program.”
Instead, in cases where it may be called multiple times, consider handling it as an asynchronous sequence.

Related

Issues with retain cycle using AsyncStream in a Task

Found this issue while working with the new Swift concurrency tools.
Here's the setup:
class FailedDeinit {
init() {
print(#function, id)
task = Task {
await subscribe()
}
}
deinit {
print(#function, id)
}
func subscribe() async {
let stream = AsyncStream<Double> { _ in }
for await p in stream {
print("\(p)")
}
}
private var task: Task<(), Swift.Error>?
let id = UUID()
}
var instance: FailedDeinit? = FailedDeinit()
instance = nil
Running this code in a Playground yields this:
init() F007863C-9187-4591-A4F4-BC6BC990A935
!!! The deinit method is never called!!!
Strangely, when I change the code to this:
class SuccessDeinit {
init() {
print(#function, id)
task = Task {
let stream = AsyncStream<Double> { _ in }
for await p in stream {
print("\(p)")
}
}
}
deinit {
print(#function, id)
}
private var task: Task<(), Swift.Error>?
let id = UUID()
}
var instance: SuccessDeinit? = SuccessDeinit()
instance = nil
By moving the code from the method subscribe() directly in the Task, the result in the console changes to this:
init() 0C455201-89AE-4D7A-90F8-D6B2D93493B1
deinit 0C455201-89AE-4D7A-90F8-D6B2D93493B1
This may be a bug or not but there is definitely something that I do not understand. I would welcome any insight about that.
~!~!~!~!
This is crazy (or maybe I am?) but with a SwiftUI macOS project. I still DON'T get the same behaviour as you. Look at that code where I kept the same definition of the FailedDeinit and SuccessDeinit classes but used them within a SwiftUI view.
struct ContentView: View {
#State private var failed: FailedDeinit?
#State private var success: SuccessDeinit?
var body: some View {
VStack {
HStack {
Button("Add failed") { failed = .init() }
Button("Remove failed") { failed = nil }
}
HStack {
Button("Add Success") { success = .init() }
Button("Remove Success") { success = nil }
}
}
}
}
class FailedDeinit {
init() {
print(#function, id)
task = Task { [weak self] in
await self?.subscribe()
}
}
deinit {
print(#function, id)
}
func subscribe() async {
let stream = AsyncStream<Double> { _ in }
for await p in stream {
print("\(p)")
}
}
private var task: Task<(), Swift.Error>?
let id = UUID()
}
Consider the following:
task = Task {
await subscribe()
}
It is true that introduces a strong reference to self. You can resolve that strong reference with:
task = Task { [weak self] in
await self?.subscribe()
}
But that is only part of the problem here. This [weak self] pattern only helps us in this case if either the Task has not yet started or if it has finished.
The issue is that as soon as subscribe starts executing, despite the weak reference in the closure, it will keep a strong reference to self until subscribe finishes. So, this weak reference is prudent, but it is not the whole story.
The issue here is more subtle than appears at first glance. Consider the following:
func subscribe() async {
let stream = AsyncStream<Double> { _ in }
for await p in stream {
print("\(p)")
}
}
The subscribe method will keep executing until the stream calls finish. But you never finish the stream. (You don’t yield any values, either. Lol.) Anyway, without anything in the AsyncStream, once subscribe starts it will never complete and thus will never release self.
So let us consider your second rendition, when you create the Task, bypassing subscribe:
task = Task {
let stream = AsyncStream<Double> { _ in }
for await p in stream {
print("\(p)")
}
}
Yes, you will see the object be deallocated, but you are neglecting to notice that this Task will never finish, either! So, do not be lulled into into a false sense of security just because the containing object was released: The Task never finishes! The memory associated with that Task will never get released (even if the parent object, FailedDeinit in your example, is).
This all can be illustrated by changing your stream to actually yield values and eventually finish:
task = Task {
let stream = AsyncStream<Double> { continuation in
Task {
for i in 0 ..< 10 {
try await Task.sleep(nanoseconds: 1 * NSEC_PER_SECOND)
continuation.yield(Double(i))
}
continuation.finish()
}
}
for await p in stream {
print("\(p)")
}
print("all done")
}
In this case, if you dismiss it while the stream is underway, you will see that the AsyncStream continues until it finishes. (And, if you happen to be doing this inside a method, the object in question will also be retained until the task is canceled.)
So, what you need to do is to cancel the Task if you want the AsyncStream to finish. And you also should implement onTermination of the continuation in such a manner that it stops the asynchronous stream.
But, the result is that if I cancel this when the view controller (or whatever) is released, then my example yielding values 0 through 9 will stop and the task will be freed.
It all comes down to what your AsyncStream is really doing. But in the process of simplifying the MCVE and removing the contents of the AsyncStream, you simultaneously do not handle cancelation and never call finish. Those two, combined, manifest the problem you describe.
This doesn't really have anything to do with async/await or AsyncStream. It's a perfectly normal retain cycle. You (the FailedDeinit instance) are retaining the task, but the task refers to subscribe which is a method of you, i.e. self, so the task is retaining you. So simply break the retain cycle just like you would break any other retain cycle. Just change
task = Task {
await subscribe()
}
To
task = Task { [weak self] in
await self?.subscribe()
}
Also, be sure to test in a real project, not a playground, as playgrounds are not indicative of anything in this regard. Here's the code I used:
import UIKit
class FailedDeinit {
init() {
print(#function, id)
task = Task { [weak self] in
await self?.subscribe()
}
}
deinit {
print(#function, id)
}
func subscribe() async {
let stream = AsyncStream<Double> { _ in }
for await p in stream {
print("\(p)")
}
}
private var task: Task<(), Swift.Error>?
let id = UUID()
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var instance: FailedDeinit? = FailedDeinit()
instance = nil
}
}

Swift: task {} before iOS 15?

I am following tutorials to understand SwiftUI, and specifically how to call an API when a view appears.
I saw this:
List(results, id: \.trackId) { item in
ListRow(item)
}
.task {
// perform API here
}
But as my app targets iOS 14, I get this error:
'task(priority:_:)' is only available in iOS 15.0 or newer
So what could I do instead? Thank you for your help
You can write a version of task { } that works for iOS 13, iOS 14 and uses apple's version for iOS 15:
extension View {
#available(iOS, deprecated: 15.0, message: "This extension is no longer necessary. Use API built into SDK")
func task(priority: TaskPriority = .userInitiated, _ action: #escaping #Sendable () async -> Void) -> some View {
self.onAppear {
Task(priority: priority) {
await action()
}
}
}
}
async await is available for iOS 13+.
https://developer.apple.com/documentation/swift/task
if you need to use an async call is wrap the call in Task
.onAppear(){
Task{
//Your async code here
// await yourFuncHere()
}
}
.onAppear is a bit un reliable so I might opt for an init of an ObservableObject as an alternative.
Just switching to .onAppear is not correct since it's missing the point of Structured Concurrency. Every time you create a Task yourself you should be suspicious, you are doing something out of the ordinary.
Granted, in this case we don't have available a "structured concurrency aware" lifecycle modifier, so we need to make our own with Task init, but that means you need to be responsible of respecting structured concurrency!
This means that getting a proper backwards compatible solution to work is a bit more code, since you want to handle cancellation properly. For that you need to use also .onDisappear and cancel the task that you started on .onAppear.
If you want to have it reusable you can make a custom .task modifier.
import SwiftUI
struct ContentView: View {
#State var results = [TaskEntry]()
var body: some View {
List(results, id: \.id) { item in
VStack(alignment: .leading) {
Text(item.title)
}
// this one onAppear you can use it
}.onAppear(perform: loadData)
}
func loadData() {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos") else {
print("Your API end point is Invalid")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let response = try? JSONDecoder().decode([TaskEntry].self, from: data) {
DispatchQueue.main.async {
self.results = response
}
return
}
}
}.resume()
}
}

MainActor and async await when reading and writing

I understand the new async syntax in Swift in the sense that if I call it, then it will handle a pool of asynchronous queues / threads (whatever) to do the work. What I don't understand is how we return to the main thread once it's all over.
// On main thread now
let manager = StorageManager()
let items = await manager.fetch // returns on main thread?
struct StorageManager {
private func read() throws -> [Item] {
let data = try file.read()
if data.isEmpty { return [] }
return try JSONDecoder().decode([Item].self, from: data)
}
func fetch() async {
fetchAndWait()
}
func fetchAndWait() {
if isPreview { return }
let items = try? read()
fetchedItems = items ?? []
}
func save() throws {
let data = try JSONEncoder().encode(fetchedItems)
try file.write(data)
}
}
I want to make sure that I read and write from/to disk in the correct way i.e. is thread safe when necessary and concurrent where possible. Is it best to declare this struct as a #MainActor ?
There is nothing in the code you've given that uses async or await meaningfully, and there is nothing in the code you've given that goes onto a "background thread", so the question as posed is more or less meaningless. If the question did have meaning, the answer would be: to guarantee that code doesn't run on the main thread, put that code into an actor. To guarantee that code does run on the main thread, put that code into a #MainActor object (or call MainActor.run).
The async methods do not return automatically to the main thread, they either:
complete in the background whatever they are doing
or
explicitly pass at a certain moment the execution to the main thread through a #MainActor function/ class. (edited following #matt's comment)
In the code above you can start by correcting the fact that fetch() does not return any value (items will receive nothing based on your code).
Example of your code for case 1 above:
let manager = StorageManager()
let items = await manager.fetch // not on the main thread, the value will be stored in the background
struct StorageManager {
private func read() throws -> [Item] {
let data = try file.read()
if data.isEmpty { return [] }
return try JSONDecoder().decode([Item].self, from: data)
}
func fetch() async -> [Item] {
if isPreview { return }
let items = try? read()
return items ?? []
}
func save() throws {
let data = try JSONEncoder().encode(fetchedItems)
try file.write(data)
}
}
Example for case 2 above (I created an #Published var, which should only be written on the main thread, to give you the example):
class ViewModel: ObservableObject {
let manager = StorageManager()
#Published var items = [Item]() // should change value only on main thread
func updateItems() {
Task { // Enter background thread
let fetchedItems = await self.manager.fetch()
// Back to main thread
updateItemsWith(fetchedItems)
}
}
#MainActor private func updateItemsWith(newItems: [Item]) {
self.items = newItems
}
}
struct StorageManager {
private func read() throws -> [Item] {
let data = try file.read()
if data.isEmpty { return [] }
return try JSONDecoder().decode([Item].self, from: data)
}
func fetch() async -> [Item] {
if isPreview { return }
let items = try? read()
return items ?? []
}
func save() throws {
let data = try JSONEncoder().encode(fetchedItems)
try file.write(data)
}
}

Update UI after async await call

I load books from API, show activity indicator while loading, update label after server response.
activityView.isHidden = false
let task = detach {
do {
let books = try await self.bookService.fetchBooks()
DispatchQueue.main.async {
self.show(books: books)
}
} catch {
DispatchQueue.main.async {
self.resultLabel.text = error.localizedDescription
}
}
DispatchQueue.main.async {
self.activityView.isHidden = true
}
}
//...
My question is what is better approach to update UI on the main queue? DispatchQueue.main.async look ugly and I guess there is a better approach to do the same.
I must use it, because all UI updates should be on the main thread and I get compiler errors without DispatchQueue.main.async something like
Property 'text' isolated to global actor 'MainActor' can not be mutated from a non-isolated context
or
Property 'isHidden' isolated to global actor 'MainActor' can not be mutated from a non-isolated context
P.S. Use Xcode 13.0b2
Use #MainActor like this -
self.updateAcitivityIndicator(isHidden: false)
let task = detach {
do {
let books = try await self.bookService.fetchBooks()
self.showBooks(books)
} catch {
self.showError(error)
}
self.updateAcitivityIndicator(isHidden: true)
}
#MainActor
private func showBooks(_ books: [Book]) {
}
#MainActor
private func showError(_ error: Error) {
self.resultLabel.text = error.localizedDescription
}
#MainActor
private func updateAcitivityIndicator(isHidden: Bool) {
self.activityView.isHidden = isHidden
}

SWIFT TASK CONTINUATION MISUSE: leaked its continuation - for delegate?

I'm trying to extend my class with async/await capabilities, but at run-time there is an error in the console:
SWIFT TASK CONTINUATION MISUSE: query(_:) leaked its continuation!
Below is the class I'm trying to add the continuation to which uses a delegate:
class LocalSearch: NSObject, MKLocalSearchCompleterDelegate {
private let completer: MKLocalSearchCompleter
private var completionContinuation: CheckedContinuation<[MKLocalSearchCompletion], Error>?
init() {
completer = MKLocalSearchCompleter()
super.init()
completer.delegate = self
}
func query(_ value: String) async throws -> [MKLocalSearchCompletion] {
try await withCheckedThrowingContinuation { continuation in
completionContinuation = continuation
guard !value.isEmpty else {
completionContinuation?.resume(returning: [])
completionContinuation = nil
return
}
completer.queryFragment = value
}
}
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
completionContinuation?.resume(returning: completer.results)
completionContinuation = nil
}
func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) {
completionContinuation?.resume(throwing: error)
completionContinuation = nil
}
}
This is how I use it:
let localSearch = LocalSearch()
do {
let results = try await localSearch.query("toront")
print(results)
} catch {
print(error)
}
What am I doing wrong or is there a better way to achieve this?
This message appears if a continuation you created via withCheckedContinuation, or withCheckedThrowingContinuation doesn't report success or failure before being discarded. This is will lead to resource leaking:
Resuming from a continuation more than once is undefined behavior. Never resuming leaves the task in a suspended state indefinitely, and leaks any associated resources. CheckedContinuation logs a message if either of these invariants is violated.
Excerpt taken from the documentation for CheckedContinuation (emphasis mine).
Here are possible causes for this to happen:
not all code paths resume the continuation, e.g. there is an if/guard/case that exits the scope without instructing the continuation to report success/failure
class Searcher {
func search(for query: String) async throws -> [String] {
await withCheckedContinuation { continuation in
someFunctionCall(withCompletion: { [weak self] in
guard let `self` = self else {
// if `result` doesn't have the expected value, the continuation
// will never report completion
return
}
continuation.resume(returning: something)
})
}
}
}
an "old"-style async function doesn't call the completion closure on all paths; this is a less obvious reason, and sometimes a harder to debug one:
class Searcher {
private let internalSearcher = InternalSearcher()
func search(for query: String) async throws -> [String] {
await withCheckedContinuation { continuation in
internalSearcher.search(query: query) { result in
// everything fine here
continuation.resume(returning: result)
}
}
}
}
class InternalSearcher {
func search(query: String, completion: #escaping ([String]) -> Void {
guard !query.isEmpty else {
return
// legit precondition check, however in this case,
// the completion is not called, meaning that the
// upstream function call will imediately discard
// the continuation, without instructing it to report completion
}
// perform the actual search, report the results
}
}
the continuation is stored as a property when a function is called; this means that if a second function call happens while the first one is in progress, then the first completion will be overwritten, meaning it will never report completion:
class Searcher {
var continuation: CheckedContinuation<[String], Error>?
func search(for query: String) async throws -> [String] {
try await withCheckedTrowingContinuation { continuation in
// note how a second call to `search` will overwrite the
// previous continuation, in case the delegate method was
// not yet called
self.continuation = continuation
// trigger the searching mechanism
}
}
func delegateMethod(results: [String]) {
self.continuation.resume(returning: results)
self.continuation = nil
}
}
#1 and #2 usually happen when dealing with functions that accept completion callbacks, while #3 usually happens when dealing with delegate methods, since in that case, we need to store the continuation somewhere outside the async function scope, in order to access it from the delegate methods.
Bottom line - try to make sure that a continuation reports completion on all possible code paths, otherwise, the continuation will indefinitely block the async call, leading to the task associated with that async call leaking its associated resources.
In your case, what likely happened is that a second query() call occurred before the first call had a chance to finish.
And in that case, the first continuation got discarded without reporting completion, meaning the first caller never continued the execution after the try await query() call, and this is not ok at all.
The following piece of code needs to be fixed, in order not to overwrite a pending continuation:
func query(_ value: String) async throws -> [MKLocalSearchCompletion] {
try await withCheckedThrowingContinuation { continuation in
completionContinuation = continuation
One quick solution would be to store an array of continuations, resume all continuations in the delegate methods, and clear the array afterward. Also, in your specific case, you could simply extract the validation out of the continuation code, as you are allowed to synchronously return/throw, even when in an async function:
func query(_ value: String) async throws -> [MKLocalSearchCompletion] {
guard !value.isEmpty else {
return []
}
return try await withCheckedThrowingContinuation { continuation in
continuations.append(continuation)
completer.queryFragment = value
}
}
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
continuations.forEach { $0.resume(returning: completer.results) }
continuations.removeAll()
}
func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) {
continuations.forEach { $0.resume(throwing: error) }
continuations.removeAll()
}
I'd also strongly recommend converting your class to an actor, in order to avoid data races, regardless if you store one continuation, like now, or you use an array. The reason is that the continuation property is consumed from multiple threads and at some point you might end up with two threads concurrently accessing/writing the property.
I think the problem is here -
func query(_ value: String) async throws -> [MKLocalSearchCompletion] {
try await withCheckedThrowingContinuation { continuation in
// storing into a variable makes this continuation instance outlive the scope of it
// In other words, it leaks OR escapes the scope
// This is same as why we need to add #escaping attribute for callback functions arguments
// those are either stored in variables like this
// or passed to other functions (escaping scope of current function)
completionContinuation = continuation
// Try commenting above line, the warning should go away
// And your code will stop working as well :)
// How to design this component is other question.
}
}
UPDATE
import MapKit
class LocalSearch: NSObject, MKLocalSearchCompleterDelegate {
typealias Completion = (_ results: [MKLocalSearchCompletion]?, _ error: Error?) -> Void
private let completer: MKLocalSearchCompleter
private var completion: Completion?
override init() {
completer = MKLocalSearchCompleter()
super.init()
completer.delegate = self
}
func query(_ value: String, completion: #escaping Completion) {
self.completion = completion
completer.queryFragment = value
}
func query(_ value: String) async throws -> [MKLocalSearchCompletion] {
try await withCheckedThrowingContinuation { continuation in
guard !value.isEmpty else {
continuation.resume(returning: [])
return
}
self.query(value, completion: { (results, error) in
if let error = error {
continuation.resume(throwing: error)
} else {
continuation.resume(returning: results ?? [])
}
})
}
}
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
completion?(completer.results, nil)
}
func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) {
completion?(nil, error)
}
}