Mega Bundle SALE is ON! Get ALL of our amazing iOS app codebases at 95% OFF discount 🔥

In today’s privacy-focused world, keeping a high bar for the security of our iOS apps, by storing critical user data securely is more important than ever. When handling sensitive user data such as passwords, in-app purchases, etc, in iOS apps, a mobile developer needs to take security into consideration. In our App Templates, we are taking security very seriously, by making it part of our core values. In this tutorial, we will show you how to use the Keychain in Swift to store sensitive user data by implementing a persistent login feature on iOS.

keychain swift

1. What is Keychain?

Keychain is storage of small, sensitive data such as passwords, bank account numbers, or some other personal information that we want to keep confidential for your users. Like OS X, iOS also provides a keychain for your application to be able to store all of the above sensitive data types. Normally, we can only use these types of information in the same application and cannot be used in other apps. So, have you ever heard about Facebook and Messenger? Just kidding. The coolest thing about two apps is that once you logged into Facebook with a registered account successfully, you can also log with the same account into Messenger. But you may wonder if we can do it, that means the account information was not secured. The app has to know the user’s email and password in order to login to Messenger – a chat application. Well, actually we can use Keychain Sharing to do that while ensuring the security. We can share the stored Keychain between many different applications on the same device which has the same Apple Developer Account. At iOS App Templates, we also have some projects with chat features like that such as iOS Dating App Template or Free Swift iOS Chat with Firebase, where we leverage this Keychain sharing feature.

2. Setting up Keychain Sharing in Swift

In this Swift tutorial, we need to create two different mobile apps to show you how to use Keychain Sharing with its powerful functionality. Let’s name these two apps TheiOSAppTemplates and TheiOSAppTemplatesBlog projects. In each project, we turn Keychain Sharing on in the Capabilities pane, as shown in the following image. Remember the value of Keychain Groups since it is used for other apps. Based on that, they can retrieve the stored values from the Keychain. After turning it on, Keychain Sharing will create a “.entitlements”  file for you: In the above file, there is a {AppIdentifierPrefix} field. This field is the Prefix (or TeamID) that is taken from the App ID in the Apple Developer Account portal. Currently, there are many open-source Swift libraries that support Keychain Storage. We could also code it by ourselves since it’s not that hard. But for simplicity and speed, we will use the KeychainSwift library, which we add as a dependency to our project with Cocoa Pods:

pod 'KeychainSwift'

In the completed source code, we actually install that pod library, so all you need to do is to download and run the Xcode project.

3. Keychain Swift Example

Before we get started, let’s describe the two applications a little bit. The first app named TheiOSAppTemplates, has a login function with username and password. After logging in successfully, it will lead you to a screen having a single button. Tapping on that button will open the second app (TheiOSAppTemplatesBlog) with the information from the first application (the username and the password). keychain sharing swift

a. Storing Data To Keychain in Swift (writing to Keychain)
Alright, let’s write the code. In the IBAction of the “Log In” button, we have
guard let userName = self.userNameTextField.text,
      let password = self.passwordTextField.text else { return }
    
let keychain = KeychainSwift()
keychain.accessGroup = "123ABCXYZ.iOSAppTemplates"
keychain.set(userName, forKey: "userName")
keychain.set(password, forKey: "password")
    
// The next flow is navigation. Basically, it pushes to ReadBlogsViewController

The code above unwrapped the values of userNameTextField and passwordTextField, then stored them into the Keychain. By setting app the accessGroup, we enable the functionality of sharing keychain data between our two applications. Obviously, do not forget to import the KeychainSwift library, so that the code compiles successfully. As you can see, with only a few simple lines of code, you saved the necessary information into the Keychain. The next step is just to navigate to ReadBlogsViewController. We left this part to you as a small challenge. Next, let’s see what we have in the ReadBlogsViewController class. In the IBAction of “Read our blogs” button, we have:

guard let appURL = URL(string: "OpenBlogApp://") else { return }
  if UIApplication.shared.canOpenURL(appURL) {
    UIApplication.shared.open(appURL)
  }

The above code helps us to open an application from another application. However, it is not enough. We need to configure the Schemes a bit. Let’s add the LSApplicationQueriesSchemes parameter to Info.plist as follows Pay attention to the type of LSApplicationQueriesSchemes. It should be of Array type instead of String.

b. Reading Data from Keychain in Swift

Let’s see how we can retrieve the information from the Keychain, in the other app. Inside viewDidLoad, we have the code below that reads from the Keychain:

let keychain = KeychainSwift()
    keychain.accessGroup = "123ABCXYZ.iOSAppTemplates"
    if let userName = keychain.get("userName"),
      let password = keychain.get("password") {
      keychainLabel.text = "userName = \(userName) password = \(password)"
    }

Easy and straightforward. Notice how we set the accessGroup, similarly to what we did for the first app. In this way, we can get the value stored in the Keychain, even if the data was written by a different app. The last step of this Keychain Swift tutorial is to configure the URL types inside Info.plist like this: This would allow the second app to be opened from the first app. Let’s run both iOS apps at the same time, and see the result. Tap on the buttons, enter the flow and notice how the data is being shared securely between two different apps within the same access group, by leveraging Keychain. persistent login swiftkeychain ioskeychain swift code

4. Conclusion

As we saw, Keychain is a powerful data storage mechanism, that supports secure data sharing between different iOS apps. We hope that after reading this article, you now have a secure way to store sensitive user information as well as to persist login credentials by using Keychain in Swift. This is a very useful functionality, if in the future you plan to develop multiple applications that are interlinked and are sharing data between them, locally. Download the complete source code here. We recommend you to try writing your own code based on our tutorial, before reading the open source Swift project. Happy Coding!


Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping Cart