How Swift Runs an Async

October 19, 2021 Publish By : EXPERT APP DEVS 2 min read Viewed By : 102
swift runs an async

What is Async?

  • Async stands for asynchronous
  • An example of a method

func fetchImages() async throws -> [UIImage] {
    // .. perform data request
}

  • ​​​​fetchImages() function is defined as asynchronous throwing, it means that performing a failable  asynchronous job. This function return a array of image and if anything get wrong its throw an error otherwise execute successfully 

How to use async let

func loadImage(index: Int) async -> UIImage {
    let imageURL = URL(string: "https://picsum.photos/200/300")!
    let request = URLRequest(url: imageURL)
    let (data, _) = try! await URLSession.shared.data(for: request, delegate: nil)
    print("Finished loading image \(index)")
    return UIImage(data: data)!
}

  • Using this we tell our application to wait for returned first image after fetch the second image 

How to use async Return Value

func uploadImage(
    image: UIImage, 
    completion: ((URLResponse?, Error?) -> Void)?
)

  • Function return completion handler 

func uploadImage(image: UIImage) 
    async throws -> URLResponse

  • Function throw URLResponse as return value 


How to use Async Await Let

  • To wait for completion of previous async let variables, use await when the let variable is required to have been initialized:

let imageResponse = try await uploadImage(
       image: image 
)

How to use Async Await

// Define an asynchronous function uploadTask that 
// will contain multiple async function calls
func uploadTask(
    image: UIImage, 
    data: Data) async throws {

// Perform the following async functions 
// at the same time
async let imageResponse = try uploadImage(
        image: image
    )

async let dataResponse = try uploadData(
        data: data
    )
    
    // Wait for completion of attachImageToData 
    // before moving forward
    try await attachImageToData(
        imageResponse: await imageResponse, 
        dataResponse: await dataResponse
    )

// Wait for completion of saveChanges 
    // before moving forward
    try await saveChanges()
}

 

 

Need a consultation?

Drop us a line! We are here to answer your questions 24/7.