Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How convert struct to string (valid url format) and then parse the same struct again from it?

I want to convert my structs to the "string" so I can add them to the URL and reread them later from another URL.

here is how I wanted to do it, but it’s not working and I have no idea why.

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")
}

Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

stringData: https:google.com/eyJumluZyI6WyJpdGVtIDEiLCJpdGVtIDIiXX0=

validURL: https:google.com/https:google.com/eyJumluZyI6WyJpdGVtIDEiLCJpdGVtIDIiXX0=

shit!

>Solution :

It’s a typo. You have to decode newData rather than newStringData

You can figure out yourself if you catch the DecodingError.

And it’s easier to get the path of the URL and drop the first – the slash – character

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?.path.dropFirst().data(using: .utf8) {
    let newData = Data(base64Encoded: newStringData)!
    do {
        let newObject = try JSONDecoder().decode(MyObject.self, from: newData)
        print("new parsed object:", newObject)
    } catch {
        print("shit!", error)
    }
} else {
    print("Oops")
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading