Gökhan Aydın
Gökhan Aydın

Reputation: 187

May not Decode .utf8 be working well in swift?

This is my string extension

extension String {

    func base64Encoded() -> String? {
        return data(using: .utf8)?.base64EncodedString()
    }

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

and I try to decode the string which is

eyJhdWQiOiIxMjM0IiwiaWF0IjoxNTMwNTM3MzQxLCJleHAiOjE1MzA1NDA5NDEsImlzcyI6Imh0dHA6Ly82O1282Dcu2jgzL2E32ko2N2ciLCJzdWIiOiIwMUNGVjZaRjA3WkhKQ1FZQVRURDFOVkM0UCIsInJscyI6WyJjb2FjaC5kcml2ZXIiXX0

to

{
  "aud": "1234",
  "iat": 1530537341,
  "exp": 1530540941,
  "iss": "http://6;]��7.�83/a7�J67g",
  "sub": "01CFV6ZF07ZHJCQYATTD1NVC4P",
  "rls": [
    "coach.driver"
  ]
}

however I haven't achieved it yet. The most strange thing about this subject, on online encode-decode converter websites, it is converted true. But in swift, I cannot do this.

Upvotes: 0

Views: 269

Answers (1)

kirti Chavda
kirti Chavda

Reputation: 3015

you Should use URl Safe encoding and decoding

extension String {
  //: ### Base64 encoding a string
  func base64Encoded() -> String? {
    if let data = self.data(using: .utf8) {
      return data.base64URLEncodedString()
    }
    return nil
  }

  //: ### Base64 decoding a string
  func base64Decoded() -> String? {


    if let data = Data(base64URLEncoded: self) {
      return String(data: data, encoding: .utf8)
    }



    return nil
  }
}
extension Data {

  init?(base64URLEncoded string: String) {
    let base64Encoded = string
      .replacingOccurrences(of: "_", with: "/")
      .replacingOccurrences(of: "-", with: "+")
    // iOS can't handle base64 encoding without padding. Add manually
    let padLength = (4 - (base64Encoded.count % 4)) % 4
    let base64EncodedWithPadding = base64Encoded + String(repeating: "=", count: padLength)
    self.init(base64Encoded: base64EncodedWithPadding)
  }

  func base64URLEncodedString() -> String {
    // use URL safe encoding and remove padding
    return self.base64EncodedString()
      .replacingOccurrences(of: "/", with: "_")
      .replacingOccurrences(of: "+", with: "-")
      .replacingOccurrences(of: "=", with: "")
  }
}

Upvotes: 1

Related Questions