如何解码Swift 5版本?

问题描述

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

我试图通过参考这两篇文章来做到这一点。但这与我要尝试的完全不同。

我引用的其他代码

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

这与我尝试执行的操作最相似,但是我不知道语法是否已发生很大变化,因为它是2015年的文字,或者我找到了错误解决方案,因此我提出了一个问题。

总而言之,我想将类似图片代码解码为base64,并将其用作简洁代码。如果您能告诉我如何(这是对little of the code的捕获。)

enter image description here

,我将不胜感激。

我的代码

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?

代码说明:创建随机UserData后,将其与data64中的值连接后将其转换为AppDelegate

解决方法

请勿使用NSString。不要使用NSMutableData。不要使用NSLog。这是Swift,不是Objective-C。使用数据。

解码已被Base 64编码的字符串的示例:

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

这可能与您尝试做的事情不同(我无法弄清您正在尝试做的事情),但这应该可以帮助您入门。只需查阅有关数据的文档。