Hallo zielen en geesten, Leo hier. The topic today is Common iOS Programming Features and how to study each of them.

This is the fourth part of my series “How to start iOS Development Career”. If you didn’t read the introduction, Part 2, and Part 3 I would strongly suggest doing so.

Today we will talk about common features of iOS development that I wanted to know before starting my career. In every tech stack, some things are commonplace and iOS development is no different. We will explore those places and what I thought was important to learn as the first iOS programming features.

If you are following the series until here, you already know how to program in Swift and how to build app interfaces, when I was in your shoes I was thinking about what more I need to start my career. So I researched with my iOS developer friends and came up with a list of things I would like to learn to feel more prepared to start my career.

Let’s go! But first…

 

Painting of The Day

Today we have an 1834 painting called Commoners near a church from Achille Pinelli. He was born in 1809 and died in 1841, and was a great Italian painter. Born in Rome, he was the son of the painter Bartolomeo Pinelli and his wife Mariangela Gatti.

Pinelli has left about two hundred watercolors painted between 1826 and 1835, preserved in the Museo di Roma, representing the facades of many churches in Rome. Liliana Barroero and Daniela Gallavotti Cavallero describe the paintings as “remaining useful iconographic documents for edifices that have been lost or since modified, and a frank description of the daily habits of Rome in the first decades of the nineteenth century: processions of Saccone, sentenced to death; street vendors; monks; nuns; police; civilians; children’s games; beggars—all animate a lively and populous city”.

And is in this mood that I chose this picture, we will talk about common features nothing is better than a painter that painted common life scenarios.

 

The problem – Common iOS Programming Features

You want to learn standard iOS features and be prepared for an iOS career.

As I said before I first researched what would be interesting things to know before starting my career. The final list was this:

  1. Learn how to store data
  2. Learn how to make network calls
  3. Learn how concurrency/parallelism works
  4. Learn Memory Management in Swift

As you can see, each of those topics is VERY big. Have sure that you will NOT master each one of those. You only need to know the basics, it is not expected that an entry-level position in regular companies (not big techs) knows how to open a web socket using InputStream and OutputStream APIs.

In the next session, we will dive into each one of those items and what I did to learn the basics of each one.

 

Storing Data in iOS

As I have a backend background I was very interested to study what iOS can provide as a solution for storing data. A big chunk of the backend job is how to deal with data and with iOS development, we deal with a lot of data too.

Generally speaking, while in backend development you are not too worried about resources, in-app development resources are gold. The user has very limited space in the device and the device has limited battery life. Also in the mobile environment, the internet connection is not guaranteed and mo you should always consider that something went wrong in the API calls.

Probably I’m forgetting something in the list below, but the main take is there are a lot of ways to store data.

When I was starting iOS my focus was on the User Defaults and Keychain. Both already provided everything I wanted to make for my homemade project so I didn’t feel the need to go further on the other kinds of storage types. The resource I used to learn was Apple documentation.

 

Options to Store Data in iOS

To store data you have some options, I will order by the simplest to the most complex:

  • In Memory: as simple as creating an array and storing it into a property this is the most volatile technique because when the app is removed from memory you will lose all the data.
  • Creating Files: You can write and read everything you need using files. You will probably use the FileManager to do that.
  • PList: Another kind of storage that is pretty similar to the files, the only difference here is that you can embed your app with PList files that you can read. In the end, they are XML files that you can easily read from your app.
  • User Defaults: this is an interface to the user’s defaults database, where you store key-value pairs persistently across launches of your app. You should NOT keep sensitive data in this storage, it is not safe. It does not provide a fancy read/write API, it is just a plain old key-value cache.
  • Keychain: Computer users often have small secrets that they need to store securely. For example, most people manage numerous online accounts. The keychain services API helps you solve this problem by giving your app a mechanism to store small bits of user data in an encrypted database called a keychain. This is a more sophisticated solution than User Defaults but still is also a plain old key-value secure cache.
  • Core Data: Persist or cache data on a single device or sync data to multiple devices with CloudKit. With core data you can: persist data between app launches, do/undo batch changes on your types, background storing tasks, versioning and migration. This is the most straightforward native solution for a local database you could look for, it has everything ( or almost ) that you will need in a local database. As stated above you can also sync multiple users’ devices this way creating a seemingly great user experience for your apps.

 

Other non-native solutions to Store Data in iOS

  • Other Database solutions: You can go with Realm or SQLite also. They both provide full database features and capabilities. Both are the most complex and that adds more extra code into your codebase, I would recommend being careful when adding such a complex solution for your apps.

 

And that was all the alternatives I can think off to study about storing data in iOS. As you are a beginner you don’t need to study all of them. Just studying the User Defaults and Keychain should be enough for getting the first job. Also, we are talking about common iOS Programming Features here not secret frameworks out there.

 

Making network calls in iOS

After studying how to store data, the next thing I thought was how to make rest calls and get data from endpoints. Good thing that Apple covered that in the URLSession class. It has everything that you need to get information from remote endpoints and crunch them into your app.

The old way was using completion closures to do our job with URLSession.

For example:

func fetchUsers(completion: @escaping (Result<[User], Error>) -> Void) {
    
    // Create URL users
    guard let url = URL(string: "https://reqres.in/api/users") else {
        completion(.failure(NetworkError.invalidURL))
        return
    }
    
    // Create URL session data task
    URLSession.shared.dataTask(with: url) { data, _ , error in
        
        if let error = error {
            completion(.failure(error))
            return
        }
        
        guard let data = data else {
            completion(.failure(NetworkError.missingData))
            return
        }
        
        do {
            // Parse the JSON data
            let userResponse = try JSONDecoder().decode(UserResponse.self, from: data)
            return userResponse.data
        } catch {
            completion(.failure(error))
        }
        
    }.resume()
}

Nowadays, we have async/await APIs that have a great syntax, check the example below:

static func fetchUsers() async throws -> [User] {
    
    guard let url = URL(string: "https://reqres.in/api/users") else {
        throw NetworkError.invalidURL
    }
    
    let (data, _) = try await URLSession.shared.data(from: url)
    
    // Parse the JSON data
    let userResponse = try JSONDecoder().decode(UserResponse.self, from: data)
    return userResponse.data
}

There is a lot happening in the lines above and it is not the scope of this article to explain it. In the future, we will explain more about async/await APIs.

In the beginning, my focus was to understand how I could make API calls and they are pretty simple in iOS, which is good for beginners like me at the time! API calls can become very tricky if you have dependents API calls, for example, you need to make an API call to get a user id, and then with that user ID, you can get all the user data.

In the beginning focus on the basics. Make a rest API call and share the results with the user. To practice that you can use the request response free api and just show users’ names. Once you can easily do that, you are done studying this part.

 

Concurrency/Paralellism in Swift

The previous topic already touched on this topic. Anyway, I wanted to make an explicit topic to study because it is a really important topic to at least know the basics. The basics I’m talking about is every time you run some operation in the background, if the result is changing something in the UI you should go back to the main thread.

Who is responsible to go the main thread? Is the code executing the background task or the coding that is calling and used in the UI? It depends, but in general, if it is a caller prerequisite that the result of the asynchronous task is run in the main queue, should be the caller to control the thread on the result. But again, this is not a rule written in stone and the answer “It depends” is valid here.

The minimum knowledge that I had to know about concurrency and parallelism in Swift was just the amount needed to perform network requests without causing troubles in the app. This way I could show that I know that I was going to a background thread but when I had the answer I should go again to the main thread.

In an interview environment, showing this basic knowledge is enough for an entry-level position. It is not expected of you to know how serial or concurrent queues works or, OperationQueue. Just knowing that UI operations should be done in the main thread, is quite enough for the first steps, in my opinion.

 

Threading Exercise of Common iOS Programming Features

A little exercise about threading for beginners is looking at the code below, what is the sequence of the names being printed in the console?

func printAll() {
    print("Pepijn")
    
    DispatchQueue.global().async {
        print("Ana")
    }
    
    print("Mike")
}

Although to be completely honest, concurrency is a topic that I like so I studied more than just that, but as I said, to start it is basic concurrency knowledge enough.

The resources I used were all in the 100 days of Swift from Paul Hudson. He explains very well about threading and when threading occurs.

 

Memory Management in Swift

This topic is interesting. Although the theory looks easy, in practice, you can fall into traps that you wouldn’t imagine exist. In this topic, you will learn about how Swift uses ARC to manage the system memory.

Every time you create a new instance of a reference type, ARC allocates a piece of memory to store information about that instance. This piece of memory holds all the information about the type of the instance, together with the values of any stored properties associated with that instance. Then when an object is no longer referenced, ARC frees up the memory used by that object so that the memory can be used for other purposes instead. This ensures that class instances don’t take up space in memory when they’re no longer needed and the memory is kept clean.

This is a gigantic topic, with a lot of edge cases and to be honest, is something that I study regularly. I would like to be better at this topic but is a work in progress for me yet.

 

Weak, unowned, and Strong in Common iOS Programming Features

Is all about using weak, unowned, and strong with your reference types. It is important because mobile devices have a very limited memory to work with and every resource saved is better for the user in the end.

A rule of thumb is: Use structs whenever you can, they don’t cause memory problems. And when you assign or pass, a reference type to properties or functions, be sure that object will be released from memory. Remember that closures are also referenced types.

This memory management part is tricky, and my advice for beginners is: in doubt use weak references. Yes, I know that ideally the developer should understand when and where capturing something weakly is mandatory or not, but in the beginning, I don’t think putting weak when in doubt hurts anyone. Better safe than sorry in this case.

As you progress in your iOS career you can learn more and more about ARC and how memory management works. Keeping a close eye on reference/retain cycles and memory leaks is an important part of your job as a developer.

There are a lot of resources about Swift Memory Management out there, and I would advise reading as much as you can until learning the basics. Be aware this is not a simple topic and it’s ok to spend time on this subject.

 

Summary – Common iOS Programming Features

Today was about some important Common iOS Programming Features that I scheduled to learn when I was beginning my iOS career. This was my path, maybe that doesn’t apply to you and maybe this can be a starting point for your list. We went through the basics of storing data, API calls, concurrency, and memory management.

There is A LOT MORE to learn on each of those topics. Be prepared for a lifelong learning journey.

This is part of the series of articles about starting your iOS career!

That’s all my people, I hope you liked reading this article as much as I enjoyed writing it. If you want to support this blog you can Buy Me a Coffee or leave a comment saying hello. You can also sponsor posts and I’m open to freelance writing! You can reach me on LinkedIn or Twitter and send me an e-mail through the contact page.

Thanks for reading and… That’s all folks.

Credits:

title image