0

I have the correctly encoded base64 string that I can decode it online, but when I use the code below and try to decode it using swift it report Unexpectedly found nil while unwrapping an Optional value error.

// the base64Code can be decode online.
let decodeBase64Code = Data(base64Encoded: base64Code)!

The base64 code

eyJyb2xlcyI6WyJVc2VyIiwiTWFpbnRhaW5lciJdLCJhdWQiOiJzdHVkZW50cyIsImV4cCI6MTYwMTk5MjU5OCwiaWF0IjoxNjAxOTg4OTk4LCJpc3MiOiJzZXJ2aWNlIHByb2plY3QiLCJzdWIiOiI0NWI1ZmJkMy03NTVmLTQzNzktOGYwNy1hNThkNGEzMGZhMmYifQ
ccd
  • 5,788
  • 10
  • 46
  • 96

1 Answers1

2

The problem with your base64 encoded string is that it is not properly terminated. You just need to add "==" to the end of your string:

let base64Code = "eyJyb2xlcyI6WyJVc2VyIiwiTWFpbnRhaW5lciJdLCJhdWQiOiJzdHVkZW50cyIsImV4cCI6MTYwMTk5MjU5OCwiaWF0IjoxNjAxOTg4OTk4LCJpc3MiOiJzZXJ2aWNlIHByb2plY3QiLCJzdWIiOiI0NWI1ZmJkMy03NTVmLTQzNzktOGYwNy1hNThkNGEzMGZhMmYifQ"

let base64CodeCount = base64Code.count
let decodedData = Data(base64Encoded: base64Code + repeatElement("=", count: base64CodeCount.isMultiple(of: 4) ? 0 : 4 - base64CodeCount % 4))!
let json = String(data: decodedData, encoding: .utf8)!  // "{"roles":["User","Maintainer"],"aud":"students","exp":1601992598,"iat":1601988998,"iss":"service project","sub":"45b5fbd3-755f-4379-8f07-a58d4a30fa2f"}"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571