Search code examples
iosswiftdecodeappdelegate

How to decode Swift 5 version?


Decode base64URL to base64 -- Swift / Decoding JSON array with codable - Swift 5

I tried to do it by referring to these two articles. But it's very different from what I'm trying to do.

Other code i referenced

let base64decryptData = NSMutableData(base64EncodedString: encodeBase64String, options: NSDataBase64DecodingOptions.allZeros)
let decodeBase64String: NSString = NSString(data: base64decryptData!, encoding: NSUTF8StringEncoding)!
    NSLog("Base64 decoding : %@", decodeBase64String)

It's the most similar to what I'm trying to do, but I don't know if the grammar has changed a lot because it's a 2015 text or if I found the wrong solution, so I'm asking a question.

To summarize, I would like to decode the code like the picture into base64 and use it as a concise code. I would appreciate if you can tell me how (This is a capture of very little of the code.)enter image description here

mycode

if let httpResponse = response as? HTTPURLResponse {
   print( httpResponse.allHeaderFields )
                                
   guard let data = data else {return}
                
   let decoder = JSONDecoder()
                
   struct UserData: Codable {
          let userId: String?
          let profile: String?
   }
                    
   do {
      let userData = try decoder.decode(UserData.self, from: data)
      DispatchQueue.main.async {
          let ad = UIApplication.shared.delegate as? AppDelegate
          ad?.paramProfile = userData.profile
          
          let base64decryptData = NSMutableData(base64EncodedString: ad?.paramProfile ?? "", options: NSData.Base64DecodingOptions) // ERROR[Cannot convert value of type 'NSData.Base64DecodingOptions.Type' to expected argument type 'NSData.Base64DecodingOptions']
          let decodeBase64String: NSString = NSString(data: base64decryptData!, encoding: NSUTF8StringEncoding)!
          print("AppDelegate - paramProfile : ",decodeBase64String )
     }

   } catch {
       print("Error:\(error)")
   }           
}

AppDelegate

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var paramId: String?
    var paramProfile: String?

Code description: After creating a random value UserData, converting it to data64 after connecting with the value in AppDelegate


Solution

  • Do not use NSString. Do not use NSMutableData. Do not use NSLog. This is Swift, not Objective-C. Use Data.

    Example of decoding a string which has been Base 64 encoded:

    let s = "d2VsbCBob3dkeSB0aGVyZQ=="
    let d = Data(base64Encoded: s)!
    let s2 = String(data: d, encoding: .utf8)!
    print(s2) // well howdy there
    

    That may not be identically what you are trying to do (I couldn't figure out what you were trying to do), but it should get you started. Just consult the documentation on Data.