我想将我的结构转换为“字符串”,以便我可以将它们添加到 URL 并稍后从另一个 URL 重新读取它们。
这就是我想做的,但它不起作用,我不知道为什么。
struct MyObject: Codable {
var number: Int
var title: String
var arrayString: [String]
}
let myObject = MyObject(number: 2, title: "hello", arrayString: ["item 1", "item 2"])
let data = try JSONEncoder().encode(myObject)
let stringData = data.base64EncodedString()
print("stringData:", stringData)
let validURL = URL(string: "https:google.com/" + stringData)
print("validURL:", validURL?.absoluteString ?? "")
if let newStringData = validURL?.absoluteString.replacingOccurrences(of: "https:google.com/", with: "").data(using: .utf8) {
let newData = Data(base64Encoded: newStringData)
if let newObject = try? JSONDecoder().decode(MyObject.self, from: newStringData) {
print("new parsed object:", newObject)
} else {
print("shit!")
}
} else {
print("Oops")
}
输出:
字符串数据:https:google.com/eyJumluZyI6WyJpdGVtIDEiLCJpdGVtIDIiXX0=
有效网址:https:google.com/https:google.com/eyJumluZyI6WyJpdGVtIDEiLCJpdGVtIDIiXX0=
妈的!
这是一个错字。你必须解码
newData
而不是 newStringData
let newData = Data(base64Encoded: newStringData)!
if let newObject = try? JSONDecoder().decode(MyObject.self, from: newData) {