Parsing Data Out of Dictionary<String, Any> in Swift - swift

I'm trying to extract data out of a Dictionary<String, Any> in Swift. The dictionary returns the following when I run NSLog("\(terminalDict)"):
Optional(["DFEE22": <323c3c>, "DFEE20": <3c>, "DFEE21": <0a>, "DFEE17": <07>, "DFEE1E": , "DF10": <656e6672 65737a68>, "9F1C": <38373635 34333231>, "DFEE16": <00>, "DFEE15": <01>, "5F36": <02>, "DF11": <00>, "DFEE1F": <80>, "DFEE18": <80>, "9F1A": <0840>, "9F35": <21>, "9F4E": <31303732 31205761 6c6b6572 2053742e 20437970 72657373 2c204341 202c5553 412e>, "DF27": <00>, "DFEE1B": <30303031 35313030>, "DF26": <01>, "9F15": <1234>, "9F40": <f000f0a0 01>, "9F16": <30303030 30303030 30303030 303030>, "9F33": <6028c8>, "9F1E": <5465726d 696e616c>])
I want to get all the keys and values out of the dictionary and into one string variable (newSettings). This is how I was attempting to do that:
for (key, value) in terminalDict! {
NSLog("key is now= \(key)")
NSLog("value is now= \(value)")
let asString = value as! String
print(asString)
NSLog("Adding \(key) \(asString)")
newSettings = "\(newSettings)\(key)\(asString)"
}
which returns:
key is now= DFEE22
value is now= {length = 3, bytes = 0x323c3c}
Could not cast value of type 'NSConcreteMutableData' (0x204aff148) to 'NSString' (0x204afde30).
How can I get the "323c3c" out of the dictionary as a simple string without the length and bytes portion? I can't find much documentation on type 'NSConcreteMutableData'. Do I have to use substring functions in order to get rid of the "length=x bytes=" part? I'm guessing there's a better way to do this than manually getting the substrings. Thanks.

As Vadian says, your dictionaries contain Data values.
It looks like it is ASCII encoded text, but it's a bit hard to be sure.
This bit:
31303732 31205761 6c6b6572 2053742e 20437970 72657373 2c204341 202c5553 412e
Represents the string "10721 Walker St. Cypress, CA ,USA." when you treat it as ASCII.
you could use code like this:
for (key, value) in terminalDict! {
NSLog("key is now= \(key)")
// Decode the data into a String assuming it's ASCII
let asString = String(data: value, encoding: .ascii)
NSLog("value is now= '\(asString)'")
print(asString)
NSLog("Adding \(key) \(asString)")
newSettings = "\(newSettings)\(key)\(asString)"
}

Related

Array (Inside of a String) Conversion, Swift 4

Does anyone know the simplest way to convert an Array inside of a String to an actual Array without effecting any characters?
For Example:
var array: [String] = []
let myStr = "[\"Hello,\", \"World\"]"
// I would like 'array' to store: ["Hello,", "World"]
I thought it could be done with Array(myStr) but that would only make an array of all the characters.
Help would be appreciated. Thank you.
You can decode it with JSONDecoder, since it is a JSON.
Example below:
let myStr = "[\"Hello,\", \"World\"]"
let data = Data(myStr.utf8)
do {
let decoded = try JSONDecoder().decode([String].self, from: data)
print("Decoded:", decoded)
} catch {
fatalError("Error")
}
// Prints: Decoded: ["Hello,", "World"]
What is happening:
Your myStr string is converted to Data.
This data is then decoded as [String] - which is an array of strings.
The decoded data of type [String] is then printed.
We use a do-try-catch pattern to catch errors, such as incorrect format or data entered.

how to read data from other Waves Oracles?

how to read data from other Waves Oracles?
getInteger(OracleAddress, key)
key is String
I don't know in what type OracleAddress i should convert to
I tried
let OracleAddress = Address("3NAcoeWdUTWn8csXJPG47v1Fjtjcfqxb5tu".toBytes())
but doesn't work
When you do toBytes() with string value you actually get bytes from UTF8 string, but in your case address is an array of bytes converted to base58, so you only need to decode it from base58:
let OracleAddress = Address(base58'3NAcoeWdUTWn8csXJPG47v1Fjtjcfqxb5tu')
getIntegerValue(OracleAddress, key)

Access data in Dictionary from NSCountedSet objects

I have an NSCountedSet consisting of String objects, if I iterate over the set and print it out, I see something like this:
for item in countedSet {
print(item)
}
Optional(One)
Optional(Two)
The countedSet is created from an Array of String objects:
let countedSet = NSCountedSet(array: countedArray)
If I print the array I see something like this:
["Optional(One)", "Optional(One)", "Optional(One)", "Optional(Two)", "Optional(Two)"]
Now, I want to use those counted strings to access data in a Dictionary, where the keys are String type and the values have the type [String : AnyObject]. If I print the dictionary, I see all the data.
However, if I use of the objects from the countedSet to access the dictionary, I always get a nil value back:
for item in countedSet {
let key = item as? String
let data = dictionary[key!] // Xcode forced me to unwrap key
print(data)
}
nil
nil
But
let key = "One"
let data = dictionary[key]
gives me the expected data.
What am I missing here, how can I access my data from the countedSet objects?
UPDATE: solved thanks to the comment from Martin R. The String objects were originally NSString objects (obtained from NSScanner), and I was casting them wrongly:
let string = String(originalString)
after I changed it to:
let string = (originalString as! String)
All works fine.

Convert UInt8 Array to String

I have decrypted using AES (CrytoSwift) and am left with an UInt8 array. What's the best approach to covert the UInt8 array into an appripriate string? Casting the array only gives back a string that looks exactly like the array. (When done in Java, a new READABLE string is obtained when casting Byte array to String).
I'm not sure if this is new to Swift 2, but at least the following works for me:
let chars: [UInt8] = [ 49, 50, 51 ]
var str = String(bytes: chars, encoding: NSUTF8StringEncoding)
In addition, if the array is formatted as a C string (trailing 0), these work:
str = String.fromCString(UnsafePointer(chars)) // UTF-8 is implicit
// or:
str = String(CString: UnsafePointer(chars), encoding: NSUTF8StringEncoding)
I don't know anything about CryptoSwift. But I can read the README:
For your convenience CryptoSwift provides two function to easily convert array of bytes to NSData and other way around:
let data = NSData.withBytes([0x01,0x02,0x03])
let bytes:[UInt8] = data.arrayOfBytes()
So my guess would be: call NSData.withBytes to get an NSData. Now you can presumably call NSString(data:encoding:) to get a string.
SWIFT 3.1
Try this:
let decData = NSData(bytes: enc, length: Int(enc.count))
let base64String = decData.base64EncodedString(options: .lineLength64Characters)
This is string output
Extensions allow you to easily modify the framework to fit your needs, essentially building your own version of Swift (my favorite part, I love to customize). Try this one out, put at the end of your view controller and call in viewDidLoad():
func stringToUInt8Extension() {
var cache : [UInt8] = []
for byte : UInt8 in 97..<97+26 {
cache.append(byte)
print(byte)
}
print("The letters of the alphabet are \(String(cache))")
}
extension String {
init(_ bytes: [UInt8]) {
self.init()
for b in bytes {
self.append(UnicodeScalar(b))
}
}
}

cannot convert a dictionary's int-value to String in swift

I have a webService, which is returning some data. here is the link http://portal.pfs-ltd.org/LoginService1114?deviceid=89A04BDB-53AA-4441-9AFD-287729ACFE7F&imeino=12345678&SerialNo=f7pln20mfpfl&username=TST0002&password=TST0002&type=agent&status=Login&flag=True&Brand=Ipad&SimSerialNumber=&TelePhoneNumber=&Model=0&InstalledVersion=1.0
I'm unable to convert the value(int) for a key to a var of type String
var ApplicationVersion: String = dict["ApplicationVersion"] as String
as is for typecasting, not converting. You need to make a string from the integer value:
let version = dict["ApplicationVersion"] as Int
let applicationVersion = "\(version)"
Note that this performs no safety checking or validation.
Your json is not a dictionary, but a nested array.
let json: [AnyObject] = ...
let dict = json[0][0] as NSDictionary
var applicationVersion = String(dict["ApplicationVersion"] as Int)