I am trying a simple exercise to demonstrate using async/await in Swift and, best that I can isolate, the app crashes when executing the Task statement. I have tried catching the exception on-throw and on-catch and the call stack does not provide any additional insight into the issue. The error is on Thread 1:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
My theory is that the COMMAND LINE template does not support Task in this simple form.
//
// main.swift
//
import Foundation
struct User {
var username: String
var movies = [Movie]()
}
struct Movie {
var title: String
var rating: Double?
}
class ManagerUsingAsync {
func getUsers() async throws -> [User] {
let allIsGood = true // Bool.random()
if allIsGood {
let users = ["mary", "casey", "theo", "dick"].map { User(username: $0) }
return users
} else {
throw URLError(.cannotConnectToHost)
}
}
func getUsersMovies(username: String) async throws -> [Movie] {
let allIsGood = true // Bool.random()
if allIsGood {
let movies = ["breaking away", "diner", "the great escape"].map { Movie(title: $0) }
return movies
} else {
throw URLError(.cannotCreateFile)
}
}
func getMovieRating(title: String) async -> Double? {
let allIsGood = true // Bool.random()
if allIsGood {
return Double.random(in: 1...10)
}
return nil
}
}
func testAsync() async -> [User] {
var _users = [User]()
let manager = ManagerUsingAsync()
do {
_users = try await manager.getUsers()
for var user in _users {
user.movies = try await manager.getUsersMovies(username: user.username)
for var movie in user.movies {
movie.rating = await manager.getMovieRating(title: movie.title)
}
}
} catch (let error) {
print(error.localizedDescription)
}
return _users
}
print("TEST ASYNC/AWAIT...")
Task {
let users = await testAsync()
for user in users {
print( "Username: \(user.username) Movies: \(user.movies)" )
}
}
Apparently this is somehow related to how my corporate MacBook is locked-down. I cannot figure this out in deeper detail, but the same code works fine (as did for #RobNapier as shared in the comments) on my personal MacBook.
Not sure if this Q should be withdrawn, but there is something to be learned about corporate MDM impact on developers (not the first time). FWIW -- My corp MacBook is managed by JAMF.
Related
I'm trying to understand async let error handling and it's not making a lot of sense in my head. It seems that if I have two parallel requests, the first one throwing an exception doesn't cancel the other request. In fact it just depends on the order in which they are made.
My testing setup:
struct Person {}
struct Animal {}
enum ApiError: Error { case person, animal }
class Requester {
init() {}
func getPeople(waitingFor waitTime: UInt64, throwError: Bool) async throws -> [Person] {
try await waitFor(waitTime)
if throwError { throw ApiError.person }
return []
}
func getAnimals(waitingFor waitTime: UInt64, throwError: Bool) async throws -> [Animal] {
try await waitFor(waitTime)
if throwError { throw ApiError.animal }
return []
}
func waitFor(_ seconds: UInt64) async throws {
do {
try await Task.sleep(nanoseconds: NSEC_PER_SEC * seconds)
} catch {
print("Error waiting", error)
throw error
}
}
}
The exercise.
class ViewController: UIViewController {
let requester = Requester()
override func viewDidLoad() {
super.viewDidLoad()
Task {
async let animals = self.requester.getAnimals(waitingFor: 1, throwError: true)
async let people = self.requester.getPeople(waitingFor: 2, throwError: true)
let start = Date()
do {
// let (_, _) = try await (people, animals)
let (_, _) = try await (animals, people)
print("No error")
} catch {
print("error: ", error)
}
print(Date().timeIntervalSince(start))
}
}
}
For simplicity, from now on I'll just past the relevant lines of code and output.
Scenario 1:
async let animals = self.requester.getAnimals(waitingFor: 1, throwError: true)
async let people = self.requester.getPeople(waitingFor: 2, throwError: true)
let (_, _) = try await (animals, people)
Results in:
error: animal
1.103397011756897
Error waiting CancellationError()
This one works as expected. The slower request, takes 2 seconds, but was cancelled after 1 second (when the fastest one throws)
Scenario 2:
async let animals = self.requester.getAnimals(waitingFor: 2, throwError: true)
async let people = self.requester.getPeople(waitingFor: 1, throwError: true)
let (_, _) = try await (animals, people)
Results in:
error: animal
2.2001450061798096
Now this one is not expected for me. The people request takes 1 second to throw an error and we still wait 2 seconds and the error is animal.
My expectation is that this should have been 1 second and people error.
Scenario 3:
async let animals = self.requester.getAnimals(waitingFor: 2, throwError: true)
async let people = self.requester.getPeople(waitingFor: 1, throwError: true)
let (_, _) = try await (people, animals)
Results in:
error: person
1.0017549991607666
Error waiting CancellationError()
Now this is expected. The difference here is that I swapped the order of the requests but changing to try await (people, animals).
It doesn't matter which method throws first, we always get the first error, and the time spent also depends on that order.
Is this behaviour expected/normal? Am I seeing anything wrong, or am I testing this wrong?
I'm surprised this isn't something people are not talking about more. I only found another question like this in developer forums.
Please help. :)
From https://github.com/apple/swift-evolution/blob/main/proposals/0317-async-let.md
async let (l, r) = {
return await (left(), right())
// ->
// return (await left(), await right())
}
meaning that the entire initializer of the async let is a single task,
and if multiple asynchronous function calls are made inside it, they
are performed one-by one.
Here is a more structured approach with behavior that makes sense.
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.padding()
.task {
let requester = Requester()
let start = Date()
await withThrowingTaskGroup(of: Void.self) { group in
let animalTask = Task {
try await requester.getAnimals(waitingFor: 1, throwError: true)
}
group.addTask { animalTask }
group.addTask {
try await requester.getPeople(waitingFor: 2, throwError: true)
}
do {
for try await _ in group {
}
group.cancelAll()
} catch ApiError.animal {
group.cancelAll()
print("animal threw")
} catch ApiError.person {
group.cancelAll()
print("person threw")
} catch {
print("someone else")
}
}
print(Date().timeIntervalSince(start))
}
}
}
The idea is to add each task to a throwing group and then loop through each task.
Cora hit the nail on the head (+1). The async let of a tuple will just await them in order. Instead, consider a task group.
But you do not need to cancel the other items in the group. See “Task Group Cancellation” discussion in the withThrowingTaskGroup(of:returning:body:) documentation:
Throwing an error in one of the tasks of a task group doesn’t immediately cancel the other tasks in that group. However, if you call
next() in the task group and propagate its error, all other tasks are
canceled. For example, in the code below, nothing is canceled and the
group doesn’t throw an error:
withThrowingTaskGroup { group in
group.addTask { throw SomeError() }
}
In contrast, this example throws SomeError and cancels all of the tasks in the group:
withThrowingTaskGroup { group in
group.addTask { throw SomeError() }
try group.next()
}
An individual task throws its error in the corresponding call to Group.next(), which gives you a chance to handle the individual error or to let the group rethrow the error.
Or you can waitForAll, which will cancel the other tasks:
let start = Date()
do {
try await withThrowingTaskGroup(of: Void.self) { group in
group.addTask { let _ = try await self.requester.getAnimals(waitingFor: 1, throwError: true) }
group.addTask { let _ = try await self.requester.getPeople(waitingFor: 2, throwError: true) }
try await group.waitForAll()
}
} catch {
print("error: ", error)
}
print(Date().timeIntervalSince(start))
Bottom line, task groups do not dictate the order in which the tasks are awaited. (They also do not dictate the order in which they complete, either, so you often have to collating task group results into an order-independent structure or re-order the results.)
You asked how you would go about collecting the results. There are a few options:
You can define group tasks such that they do not “return” anything (i.e. child of Void.self), but update an actor (Creatures, below) in the addTask calls and then extract your tuple from that:
class ViewModel1 {
let requester = Requester()
func fetch() async throws -> ([Animal], [Person]) {
let results = Creatures()
try await withThrowingTaskGroup(of: Void.self) { group in
group.addTask { try await results.update(with: self.requester.getAnimals(waitingFor: animalsDuration, throwError: shouldThrowError)) }
group.addTask { try await results.update(with: self.requester.getPeople(waitingFor: peopleDuration, throwError: shouldThrowError)) }
try await group.waitForAll()
}
return await (results.animals, results.people)
}
}
private extension ViewModel1 {
/// Creatures
///
/// A private actor used for gathering results
actor Creatures {
var animals: [Animal] = []
var people: [Person] = []
func update(with animals: [Animal]) {
self.animals = animals
}
func update(with people: [Person]) {
self.people = people
}
}
}
You can define group tasks that return enumeration case with associated value, and then extracts the results when done:
class ViewModel2 {
let requester = Requester()
func fetch() async throws -> ([Animal], [Person]) {
try await withThrowingTaskGroup(of: Creatures.self) { group in
group.addTask { try await .animals(self.requester.getAnimals(waitingFor: animalsDuration, throwError: shouldThrowError)) }
group.addTask { try await .people(self.requester.getPeople(waitingFor: peopleDuration, throwError: shouldThrowError)) }
return try await group.reduce(into: ([], [])) { previousResult, creatures in
switch creatures {
case .animals(let values): previousResult.0 = values
case .people(let values): previousResult.1 = values
}
}
}
}
}
private extension ViewModel2 {
/// Creatures
///
/// A private enumeration with associated types for the types of results
enum Creatures {
case animals([Animal])
case people([Person])
}
}
For the sake of completeness, you don't have to use task group if you do not want. E.g., you can manually cancel earlier task if prior one canceled.
class ViewModel3 {
let requester = Requester()
func fetch() async throws -> ([Animal], [Person]) {
let animalsTask = Task {
try await self.requester.getAnimals(waitingFor: animalsDuration, throwError: shouldThrowError)
}
let peopleTask = Task {
do {
return try await self.requester.getPeople(waitingFor: peopleDuration, throwError: shouldThrowError)
} catch {
animalsTask.cancel()
throw error
}
}
return try await (animalsTask.value, peopleTask.value)
}
}
This is not a terribly scalable pattern, which is why task groups might be a more attractive option, as they handle the cancelation of pending tasks for you (assuming you iterate through the group as you build the results).
FWIW, there are other task group alternatives, too, but there is not enough in your question to get too specific in this regard. For example, I can imagine some protocol-as-type implementations if all of the tasks returned an array of objects that conformed to a Creature protocol.
But hopefully the above illustrate a few patterns for using task groups to enjoy the cancelation capabilities while still collating the results.
I have a problem running multiply tasks in parallel in a SwiftUI view.
struct ModelsView: View {
#StateObject var tasks = TasksViewModel()
var body: some View {
NavigationView{
ScrollView {
ForEach(Array(zip(tasks.tasks.indices, tasks.tasks)), id: \.0) { task in
NavigationLink(destination: ModelView()) {
ModelPreviewView(model_name: "3dobject.usdz")
.onAppear {
if task.0 == tasks.tasks.count - 2 {
Task {
print(tasks.tasks.count)
await tasks.fetch_tasks(count: 4)
}
}
}
}
}
}.navigationTitle("3D modelle")
}.onAppear{
Task {
await tasks.fetch_tasks(count: 5)
await tasks.watch_for_new_tasks()
}
}
}
}
In my view, I spawn a task as soon as the View Appears which, first, fetches 5 tasks from the database (this works fine), and then it starts watching for new tasks.
In the Scroll View, right before the bottom is reached, I start loading new tasks. The problem is, the asynchronous function fetch_tasks(count: 4) only gets continued if the asynchronous function watch_for_new_tasks() stops blocking.
actor TasksViewModel: ObservableObject {
#MainActor #Published private(set) var tasks : [Tasks.Task] = []
private var last_fetched_id : String? = nil
func fetch_tasks(count: UInt32) async {
do {
let tasks_data = try await RedisClient.shared.xrevrange(streamName: "tasks", end: last_fetched_id ?? "+" , start: "-", count: count)
last_fetched_id = tasks_data.last?.id
let fetched_tasks = tasks_data.compactMap { Tasks.Task(from: $0.data) }
await MainActor.run {
withAnimation(.easeInOut) {
self.tasks.append(contentsOf: fetched_tasks)
}
}
} catch {
print("Error fetching taskss \(error)")
}
}
func watch_for_new_tasks() async {
while !Task.isCancelled {
do {
let tasks_data = try await RedisClient.shared.xread(streams: "tasks", ids: "$")
let new_tasks = tasks_data.compactMap { Tasks.Task(from: $0.data) }
await MainActor.run {
for new_task in new_tasks.reversed() {
withAnimation {
self.tasks.insert(new_task, at: 0)
}
}
}
} catch {
print(error)
}
}
}
...
}
The asynchronous function watch_for_new_tasks() uses RedisClient.shared.xread(streams: "tasks", ids: "$") which blocks until at least one tasks is added to the Redis Stream.
This is my redis client:
class RedisClient {
typealias Stream = Array<StreamElement>
static let shared = RedisClient(host: "127.0.0.1", port: 6379)
let connection: Redis
let host: String
let port: Int32
init(host: String, port: Int32) {
connection = Redis()
self.host = host
self.port = port
connection.connect(host: host, port: port) {error in
if let err = error {
print(err)
}
}
}
func connect() {
connection.connect(host: self.host, port: self.port) {error in
if let err = error {
print(err)
}
}
}
func xrevrange(streamName: String, end: String, start: String, count: UInt32 = 0) async throws -> Stream {
try await withCheckedThrowingContinuation { continuation in
connection.issueCommand("xrevrange", streamName, end, start, "COUNT", String(count)) { res in
switch res {
case .Array(let data):
continuation.resume(returning: data.compactMap { StreamElement(from: $0) } )
case .Error(let error):
continuation.resume(throwing: ResponseError.RedisError(error))
case _:
continuation.resume(throwing: ResponseError.WrongData("Expected Array"))
}
}
}
}
func xread(streams: String..., ids: String..., block: UInt32 = 0, count: UInt32 = 0) async throws -> Stream {
return try await withCheckedThrowingContinuation({ continuation in
var args = ["xread", "BLOCK", String(block),"COUNT", String(count),"STREAMS"]
args.append(contentsOf: streams)
args.append(contentsOf: ids)
connection.issueCommandInArray(args){ res in
print(res)
switch res.asArray?[safe: 0]?.asArray?[safe: 1] ?? .Error("Expected response to be an array") {
case .Array(let data):
continuation.resume(returning: data.compactMap { StreamElement(from: $0) } )
case .Error(let error):
continuation.resume(throwing: ResponseError.RedisError(error))
case _:
continuation.resume(throwing: ResponseError.WrongData("Expected Array"))
}
}
})
}
func xreadgroup(group: String, consumer: String, count: UInt32 = 0, block: UInt32 = 0, streams: String..., ids: String..., noAck: Bool = true) async throws -> Stream {
try await withCheckedThrowingContinuation({ continuation in
var args = ["xreadgroup", "GROUP", group, consumer, "COUNT", String(count), "BLOCK", noAck ? nil : "NOACK", String(block), "STREAMS"].compactMap{ $0 }
args.append(contentsOf: streams)
args.append(contentsOf: ids)
connection.issueCommandInArray(args){ res in
print(res)
switch res.asArray?[safe: 0]?.asArray?[safe: 1] ?? .Error("Expected response to be an array") {
case .Array(let data):
continuation.resume(returning: data.compactMap { StreamElement(from: $0) } )
case .Error(let error):
continuation.resume(throwing: ResponseError.RedisError(error))
case _:
continuation.resume(throwing: ResponseError.WrongData("Expected Array"))
}
}
})
}
enum ResponseError: Error {
case RedisError(String)
case WrongData(String)
}
struct StreamElement {
let id: String
let data: [RedisResponse]
init?(from value: RedisResponse) {
guard
case .Array(let values) = value,
let id = values[0].asString,
let data = values[1].asArray
else { return nil }
self.id = id.asString
self.data = data
}
}
}
I tried running the watch_for_new_tasks() on a Task.detached tasks, but that also blocks.
To be honest, I have no idea why this blocks, and I could use your guy's help if you could.
Thank you in Advance,
Michael
.onAppear {
Task {
await tasks.fetch_tasks(count: 5)
await tasks.watch_for_new_tasks()
}
}
This does not run tasks in parallel. For the 2nd await to execute, the 1st one has to finish.
You can use .task modifier
You code can be refactored into this to run 2 async functions in parallel:
.task {
async let fetchTask = tasks.fetch_tasks(count: 5)
async let watchTask = tasks.watch_for_new_tasks()
}
You can do:
await [fetchTask, watchTask]
if you need to do something after both of them complete
a property from a singleton is nil when checkin is value.
calling this function from viewDidLoad like this
Task {
do {
try await CXOneChat.shared.connect(environment: .NA1, brandId: 1111, channelId: "keyID")
self.checkForConfig()
} catch {
print(error.localizedDescription)
}
}
this connect function checks for several issues and load from network the config
public func connect(environment: Environment, brandId: Int, channelId: String) async throws {
self.environment = environment
self.brandId = brandId
self.channelId = channelId
try connectToSocket()
channelConfig = try await loadChannelConfiguration()
generateDestinationId()
generateVisitor()
if customer == nil {
customer = Customer(senderId: UUID().uuidString, displayName: "")
try await authorizeCustomer()
} else if authorizationCode.isEmpty{
try await reconnectCustomer()
} else {
try await authorizeCustomer()
}
}
this work ok the self.checkForConfig does some stuff with config in singleton object.
after tapping a button and go for another ViewController. call this func
func loadThread() {
do {
if CXOneChat.shared.getChannelConfiguration()?.settings.hasMultipleThreadsPerEndUser ?? false {
try CXOneChat.shared.loadThreads()
} else {
try CXOneChat.shared.loadThread()
}
} catch {
print(error)
}
}
depending on the config call one or another config value load one or the function. in this case the getChannelConfiguration() is nil and call to loadThread().
func loadThread(threadId: UUID? = nil) throws {
guard let config = channelConfig else {
throw CXOneChatError.missingChannelConfig
}
let eventType = config.isLiveChat ? EventType.recoverLivechat : EventType.recoverThread
guard let brandId = brandId else { throw CXOneChatError.invalidBrandId }
guard let channelId = channelId else { throw CXOneChatError.invalidChannelId }
guard let id = getIdentity(with: false) else { throw CXOneChatError.invalidCustomerId }
let retrieveThread = EventFactory.shared.recoverLivechatThreadEvent(brandId: brandId, channelId: channelId, customer: id, eventType: eventType, threadId: threadId)
guard let data = getDataFrom(retrieveThread) else { throw CXOneChatError.invalidData }
let string = getStringFromData(data)
socketService.send(message: string)
}
here checks for he config in singleton object but throws error because config is nil.
my question is why is nil config in this check. the config is downloaded and store. but when get the values got a null value. Im missing some code here or what I is wrong with this.
I am new to Firebase and Swift. My previous question was very vague due to a misunderstanding on my part. In a class named "A" for example I am trying to create an object of class "B" that contains the fetchARImageTargets function that I have below. I am trying to assign the array ARImageTargets to a var in class "A" however, the listAll completion is not returned in time, which results in the var being empty. Is there a way that I can edit my function or class to avoid the var being set prematurely?
let ARImageTargetStorageRef = Storage.storage().reference().child("ImageTargets")
self.fetchARImageTargets(ref: ARImageTargetStorageRef)
func fetchARImageTargets(ref: StorageReference) {
ref.listAll { (result, error) in
if let error = error {
print(error)
}
for prefix in result.prefixes {
self.fetchARImageTargets(ref: prefix)
}
for item in result.items {
item.getMetadata { (metadata, error) in
if let error = error {
print(error)
} else {
var imageTarget = ARImageTarget()
item.downloadURL(completion: { (url, error) in
imageTarget.ImageURL = url
})
imageTarget.Id = metadata?.customMetadata?["Id"] as String?
let width = metadata?.customMetadata?["PhysicalWidth"] as String?
imageTarget.PhysicalWidth = CGFloat(truncating: NumberFormatter().number(from: width!)!)
self.ARImageTargets.append(imageTarget)
}
}
}
}
}
I want to add a value to Firestore. When finished I want to return the added value. The value does get added to Firestore successfully. However, the value does not go through sink.
This is the function that does not work:
func createPremium(user id: String, isPremium: Bool) -> AnyPublisher<Bool,Never> {
let dic = ["premium":isPremium]
return Future<Bool,Never> { promise in
self.db.collection(self.dbName).document(id).setData(dic, merge: true) { error in
if let error = error {
print(error.localizedDescription)
} else {
/// does get called
promise(.success(isPremium))
}
}
}.eraseToAnyPublisher()
}
I made a test function that works:
func test() -> AnyPublisher<Bool,Never> {
return Future<Bool,Never> { promise in
promise(.success(true))
}.eraseToAnyPublisher()
}
premiumRepository.createPremium(user: userID ?? "1234", isPremium: true)
.sink { receivedValue in
/// does not get called
print(receivedValue)
}.cancel()
test()
.sink { recievedValue in
/// does get called
print("Test", recievedValue)
}.cancel()
Also I have a similar code snippet that works:
func loadExercises(category: Category) -> AnyPublisher<[Exercise], Error> {
let document = store.collection(category.rawValue)
return Future<[Exercise], Error> { promise in
document.getDocuments { documents, error in
if let error = error {
promise(.failure(error))
} else if let documents = documents {
var exercises = [Exercise]()
for document in documents.documents {
do {
let decoded = try FirestoreDecoder().decode(Exercise.self, from: document.data())
exercises.append(decoded)
} catch let error {
promise(.failure(error))
}
}
promise(.success(exercises))
}
}
}.eraseToAnyPublisher()
}
I tried to add a buffer but it did not lead to success.
Try to change/remove .cancel() method on your subscriptions. Seems you subscribe to the publisher, and then immediately cancel the subscription. The better option is to retain and store all your subscriptions in the cancellable set.