1

I'm trying to create a Base64-String in Swift. I have an example of a Base64-encoded string and its array-counterpart. My problem now is, that I don't know how I get an equivalent array to the one which is given in the example.

Because I didn't want to mess around in my XCode-project I did the following in a playground.

given array:

{"WHERE":{"Class":"%3f","Location":"3b"},"ORDER":["Day ASC","Location DESC"]}

given Base64-string:

eyJXSEVSRSI6eyJDbGFzcyI6IiUzZiIsIkxvY2F0aW9uIjoiM2IifSwiT1JERVIiOlsiRGF5IEFTQyIsIkxvY2F0aW9uIERFU0MiXX0=

First I'm decoding the example-string

let str = "eyJXSEVSRSI6eyJDbGFzcyI6IiUzZiIsIkxvY2F0aW9uIjoiM2IifSwiT1JERVIiOlsiRGF5IEFTQyIsIkxvY2F0aW9uIERFU0MiXX0="

let data = NSData(base64EncodedString: str, options: NSDataBase64DecodingOptions(rawValue: 0))

do {
    let result = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
} catch let error {
    print(error)
}
//"result" is ["WHERE": ["Class": "%3f", "Location": "3b"], "ORDER": ["Day ASC", "Location DESC"]]

Below I'm trying to reproduce the string from above

var array = [String : AnyObject]()
var arrayPartA = [String : String]()
arrayPartA["Class"] = "%3f"
arrayPartA["Location"] = "3b"
array["ORDER"] = ["Day ASC", "Location DESC"]
array["WHERE"] = arrayPartA
array //The playground says that "array" is ["ORDER": ["Day ASC", "Location DESC"], "WHERE": ["Class": "%3f", "Location": "3b"]]
      //"ORDER" and "WHERE" are switched but I don't get them to be at the right position

let utf8str2: NSData = String(array).dataUsingEncoding(NSUTF8StringEncoding)!

let encodedStr = utf8str2.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
//Here "encodedStr" is WyJPUkRFUiI6ICgKICAgICJEYXkgQVNDIiwKICAgICJMb2NhdGlvbiBERVNDIgopLCAiV0hFUkUiOiB7CiAgICBDbGFzcyA9ICIlM2YiOwogICAgTG9jYXRpb24gPSAzYjsKfV0=
//but it should be eyJXSEVSRSI6eyJDbGFzcyI6IiUzZiIsIkxvY2F0aW9uIjoiM2IifSwiT1JERVIiOlsiRGF5IEFTQyIsIkxvY2F0aW9uIERFU0MiXX0=

I would be glad if someone could explain to me what I'm doing wrong and how I can reproduce the given Base64-string.

Since I'm new to this website I apologize in advance for wrong layout or other possible conventions I don't know.

4 Answers 4

3

Could you try this please? Is this what you wanted to do? It should convert a Dictionary to base64 String

func jsonToBaseString (yourJSON: [String: String]) -> String? {
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: yourJSON, options: JSONSerialization.WritingOptions.prettyPrinted)
        return
            jsonData.base64EncodedString(options: .endLineWithCarriageReturn)
    } catch {
        return nil
    }
}

Dictionary is Swifts JSON representation...

Sign up to request clarification or add additional context in comments.

Comments

1

Two important things to understand:

  • What you are calling an array is not an array, it's a JSON dictionary (containing an array for the ORDER key).

Be careful not to confuse the syntax of arrays and dictionaries between Swift and JSON.

In Swift, an array: [0, 1], a dictionary: ["a":0, "b":1].

In JSON, an array: [0, 1], a dictionary: {"a":0, "b":1}.

  • A Swift dictionary is an unordered collection. There's no "position" for key-value pairs.

Comments

0

You'll need to change several things:

  1. Your input string (not serialized) is not an array, but a JSON object.
  2. Try constructing your string with a proper JSON library, such as SwiftyJSON.
  3. String(array) is not enough to consistently convert your objects to strings. You should use a JSON serializer (such as SwiftyJSON json.rawString()).

Comments

0

let follow recommendation to use some json serialization, but take in account that

{
    "alfa": 1,
    "beta": true
}

and

{"beta":true,"alfa":1}

represents in JSON notation the same object even though their string representation ( doesn't matter if base64 encoded or not ) are different.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.