Encoding/decoding arbitrary binary data to string in swift/objective-c - ios

I need to encode/decode an arbitrary NSData object into a String/NSString. Here's what I have for encoding:
var avatar64 = self.avatar.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!);
let avatarData = NSData(base64EncodedString: avatar64, options: NSDataBase64DecodingOptions.fromRaw(0)!);
let avatar = NSString(data: avatarData, encoding: NSUTF8StringEncoding);
But avatar is nil. What am I doing wrong?

Your first step already creates a Base64-encoded string of the data in self.avatar:
var avatar64 = self.avatar.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!);
Your second step decodes the Base64 string again, so that avatarData contains the same
binary data as your original self.avatar:
let avatarData = NSData(base64EncodedString: avatar64, options: NSDataBase64DecodingOptions.fromRaw(0)!);
Finally, your third step tries to create a string from the original (binary) data:
let avatar = NSString(data: avatarData, encoding: NSUTF8StringEncoding);
This fails because the data is not a valid UTF-8 sequence.
In short: Just remove the third and second line.

Related

Removing unnecessary JSON spaces

I have encoded a Codable object:
let encodedData = try JSONEncoder().encode(someObject)
And I print the JSON by doing the following (I know its not safe, I'm just testing):
let json = try! JSONSerialization.jsonObject(with: encodedData)
print("JSON: \(json)")
My JSON has lots of spaces. I want a way to remove these spaces, to save space on the encoded String. You can tell that it looks quite different from a normal JSON due to these spaces.
JSON (part of it):
How can I reduce the spaces to reduce the bytes this takes up?
As #Martin R pointed out, I was not printing the JSON properly. It should have instead been:
let jsonString = String(data: encodedData, encoding: .utf8)!
print(jsonString)
The result looks like so:
{"type":1,"modifiers":[],"parameters":{ ...
This printed data can then be decoded in the future like so:
let data = Data(jsonString.utf8)
let someResult = try JSONDecoder().decode(SomeType.self, from: data)

Decode Data that is base64String to String utf Swift

A library save a token as Data in UserDefaults
//loading the token
if let token = UserDefaults.standard.object(forKey: "token") as? Data {
let base64Encoded = token.base64EncodedData
let base64EncodedString = token.base64EncodedString()
}
When I print that base64Encoded value in the console I get the value: Y2E2N2Y5NTItNDVkOC00YzZkLWFkZDMtZGRiMjc5NGE3YWI2OjdmZDU1ZTAyLWExMjEtNGQ1ZC05N2MzLWM5OWY4NTg5NTIzNg== as Data
When I copy this value from the output in the console and use this website https://www.base64decode.org/ I got the expected result. ca67f952-45d8-4c6d-add3-ddb2794a7ab6:7fd55e02-a121-4d5d-97c3-c99f85895236
My problem is that I don't get convert that base64Encoded to String in my code.
When I use base64EncodedString I got a string, but I can't figure out which format this is: PFsYdirs21247rRG/XcWOVGUGUcCCTzXz7VFAnunLJU= The method base64EncodedString() This is an method from Apple: https://developer.apple.com/documentation/foundation/nsdata/1413546-base64encodedstring
When I decode this value to utf8 at the website I got: <[v*]Fw9QG
When I try to convert my base64Encoded (Data, not String) to a string like this
if let toString = String(data: base64Encoded, encoding: String.Encoding.utf8) as String {
print("test \(toString)")
}
my compiler threw an error: Cannot convert value of type(Data.Base64EncodingOptions) -> Data to expected argument type Data
Here I found a solution to decode when my Data-value would be a string.
https://stackoverflow.com/a/31859383/4420355
So I'm quite confused about the results. Long story short:
I have base64Encoded Data (Y2E2N2Y5NTItNDVkOC00YzZkLWFkZDMtZGRiMjc5NGE3YWI2OjdmZDU1ZTAyLWExMjEtNGQ1ZC05N2MzLWM5OWY4NTg5NTIzNg==) and want them convert to an utf8 string. I don't get handle this.

Parse UTF8 json file in swift not work correctly with SwiftyJson

I tried to load UTF8 JSON file in swift and I received response in NSData. Then I converted it to NSString by:
let responseString = NSString(data: myNSdata!, encoding: NSUTF8StringEncoding)
let json = JSON(responseString)
print(json["now"].string)
print(json.string)
First print show nil but second print show file correctly but there is \ char before each " and I think this is the reason. Please help me to find solution.
No need to make a string to init JSON(), do it with the data:
let json = JSON(data: myNSdata!)

Cannot convert empty array of arrays to JSON with Swift 2

What is wrong with this piece of code (which was inspired by this example)? It currently prints JSON string "(<5b5d>, 4)" instead of the expected "[]".
var tags: [[String]] = []
// tags to be added later ...
do {
let data = try NSJSONSerialization.dataWithJSONObject(tags, options: [])
let json = String(data: data, encoding: NSUTF8StringEncoding)
print("\(json)")
}
catch {
fatalError("\(error)")
}
Short answer: The creation of the JSON data is correct. The problem is in the
conversion of the data to a string, what you want is the NSString method:
let json = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
which produces the expected [].
Slightly longer answer:
Your code
let json = String(data: data, encoding: NSUTF8StringEncoding)
calls the String init method
/// Initialize `self` with the textual representation of `instance`.
/// ...
init<T>(_ instance: T)
and the result is the textual representation of the tuple
(data: data, encoding: NSUTF8StringEncoding):
(<5b5d>, 4)
Actually you can call String() with arbitrary arguments
let s = String(foo: 1, bar: "baz")
print(s) // (1, "baz")
in Swift 2. This does not compile in Swift 1.2, so I am not sure if
this is intended or not. I have posted a question in the
Apple Developer Forums about that:
String init accepts arbitrary arguments.

How to retrieve data from Dictionary using swift and store in a string type?

I am creating iOS Application using swift.
XCODE version 6.3
I am storing NSData in NSString.This is the code for that.
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
Now the strData contains value like this.
**strData: Optional({"result":true,"user_id":2,"role_id":2,"msg":"Signed in successfully.”})**
I want to store the user_id and role_id in 2 separate strings.
For that First of all i changed NSString to normal String in Swift
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
as String?
when we print strData output will be like this.
**strData: Optional("{\"result\":true,\"user_id\":2,\"role_id\":2,\"msg\":\"Signed in successfully.\"}”)**
In my view,the string is in the format of dictionary[Key value pair]
So i created a dictionary like this,
var lognInDetails = Dictionary<Int, String>()
self.lognInDetails[1] = strData
And store string to the Dictionary.
this all working fine
The problem is i want to retrieve the value from dictionary based on the key.
For user_id key i want to store value 2.
I used this code,
self.userid = self.lognInDetails[ 1 , "user_id"] as Dictionary<Int, String>
Here userid is a String variable.
I am just a starter in swift.I am interested to learn more about both swift & objective-C.Thank For your Help.
you can directly convert NSData to NSDictionary & then set Strings with values of them.To convert NSdata to NSDictionary use
let jsonDict = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as NSDictionary
let userId = json?["user_id"]?.integerValue

Resources