Member-only story

Swift: Read file on iOS, Closure vs Combine vs async-await

Yi ๐Ÿ๐Ÿ
3 min readSep 9, 2022

--

Photo by Fotis Fotopoulos on Unsplash

Reading files could be a common task in our daily dev life. The data from a file could be a sample of JSON result for testing, or it could be the preview image of your appโ€™s UI. In this article, weโ€™ll walk through diff ways to read the file based on the framework/technology we choose here.

A. Read with Combine

Ever since Combine framework has been introduced by Apple with iOS 13, it has been widely adapted to handle values from asynchronous events. This could be ideal solution to nested closures, which could be a mess and hard to track. So, to implement File Read with Combine, we need to

  1. Create a customized Publisher, which take File URL as the input while Data as the output.
  2. Create a customized Subscription, which actually do the file reading.

Here is the code:

This code mainly copied from AdvancedSwift, please check for reference.

B. Read with Closure

--

--

Yi ๐Ÿ๐Ÿ
Yi ๐Ÿ๐Ÿ

Written by Yi ๐Ÿ๐Ÿ

Write the Code, Change the World.

Responses (2)