How can I encode a string to Base64 in Swift?


In Swift, you can use the built-in Data type and its method base64EncodedString() to encode a string to Base64. In the iOS applications, you might need to encode a string to base64 mostly in networking requests and responses. Mostly, you will need to encode a string to base64 and vice versa. Let's learn how to encode a string to Base64 using Swift.

Example

In this example, we will use the following steps to encode a string to base64 −

  • Step 1 − In this step, we will convert the string to a Data object using the data(using: .utf8) method. In this method, we pass utf8 as the encoding parameter as this is the most common encoding approach.

  • Step 2 − In this step, we call the base64EncodedString method to convert the data object to a Base64 encoded string. Remember that the data(using:) method returns an optional data object. You can use optional binding to unwrap it.

import Foundation
let stringToEncode = "This is a sample string to encode in Base64 in Swift."
if let data = stringToEncode.data(using: .utf8) {
   let base64String = data.base64EncodedString()
   print(base64String)
}

Output

VGhpcyBpcyBhIHNhbXBsZSBzdHJpbmcgdG8gZW5jb2RlIGluIEJhc2U2NCBpbiBTd2lmdC4=

Example

Another Example of Encoding a String to Base64, Decoding it Back to its Original String form, and Handling errors that might Occur −

  • Step 1 − In the first step, we will define an input string variable called "originalString" and encode it to Base64 using the data.base64EncodedString() method as before. As previously, we did two steps to encode the input string.

  • Step 2 − After decoding the input string. We will use the Data(base64Encoded:) initializer method to convert the Base64 string to a Data object.

  • Step 3 − If the initializer returns a non-nil Data object, we use the String(data:encoding:) initializer to create a string from the Data object.

import Foundation
let originalString = "This is a sample string to encode in Base64 in Swift."
// Encode the string to Base64
if let data = originalString.data(using: .utf8) {
       
   let base64String = data.base64EncodedString()
   print("Base64-encoded string: \(base64String)")
       
   // Decode the Base64-encoded string back to the original string
   if let decodedData = Data(base64Encoded: base64String) {
      if let decodedString = String(data: decodedData, encoding: .utf8) {
         print("Decoded string: \(decodedString)")
      } else {
         print("Error decoding data: could not convert decoded data to string.")
      }
   } else {
      print("Error decoding base64-encoded string: could not create decoded data.")
   }
} else {
   print("Error encoding string: could not create data.")
}

Output

Base64-encoded string: VGhpcyBpcyBhIHNhbXBsZSBzdHJpbmcgdG8gZW5jb2RlIGluIEJhc2U2NCBpbiBTd2lmdC4=
Decoded string: This is a sample string to encode in Base64 in Swift.

Decoding, however, might not succeed if the data being decoded cannot be transformed into a string or if the Base64-encoded text is incorrect. We use optional binding to manage these situations and print error messages when any of the actions go wrong.

To guarantee that the data is correctly translated to and from string form, it should be noted that we specify the .utf8 encoding when using the Data and String initializers.

Recommended Approach

Extensions are more powerful in Swift. We will create an extension to String along with some methods to encode and decode strings. Here is an extension −

import Foundation
extension String {
   func base64Encoded() -> String? {
      data(using: .utf8)?.base64EncodedString()
   }
   func base64Decoded() -> String? {
      guard let data = Data(base64Encoded: self) else { return nil }
      return String(data: data, encoding: .utf8)
   }
}

Example

Here is an Example of Using the Above Extension

let originalString = "This is a sample string to encode in Base64 in Swift."
if let encodedString = originalString.base64Encoded() {
   print("Encoded String: \(encodedString)")
    
   if let decodedString = encodedString.base64Decoded() {
      print("Decoded String: \(decodedString)")
   }
}

Output

Encoded String: VGhpcyBpcyBhIHNhbXBsZSBzdHJpbmcgdG8gZW5jb2RlIGluIEJhc2U2NCBpbiBTd2lmdC4=
Decoded String: This is a sample string to encode in Base64 in Swift.

In the above example, we created an extension to String to encode and decode strings. It looks neat and well-organized. You can use this extension throughout your application. In the case of duplicate code, it is not necessary to write it everywhere.

Conclusion

Using the Data type and its base64EncodedString() method, it is simple to encode a string to Base64 in Swift. Decoding a Base64-encoded string back to its original form requires establishing a Data object from the encoded string using the Data(base64Encoded:) initializer, and then creating a string from the Data object using the String(data:encoding:) initializer.

It's crucial to employ optional binding and look for nil values to manage potential encoding or decoding issues. When converting data into and out of string form, it's crucial to use the proper encoding; strings are commonly encoded with the.utf8 encoding.

Updated on: 04-Apr-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements