I want to convert [String] to NSData for BLE Connection.
I know how to convert String to NSData / NSData to String.
// String -> NSData
var str: String = "Apple";
let data: NSData = str.dataUsingEncoding(NSUTF8StringEncoding)!
// NSData -> String
var outStr: String = NSString(data:data, encoding:NSUTF8StringEncoding) as! String
However, how can I convert,,
// [String] -> NSData ???
let strs: [String] = ["Apple", "Orange"]
This is a sample of converting [UInt8] <--> NSData https://gist.github.com/nolili/2bf1a701df1015ed6488
I want to convert [String] <--> NSData
// [String] -> NSData ??? Is it correct???
var strs: [String] = ["Apple", "Orange"]
let data2 = NSData(bytes: &strs, length: strs.count)
// NSData -> [String] ... please teach me..
Swift 4.2
[String]
-> JSON
-> Data
func stringArrayToData(stringArray: [String]) -> Data? {
return try? JSONSerialization.data(withJSONObject: stringArray, options: [])
}
Data
-> JSON
-> [String]
func dataToStringArray(data: Data) -> [String]? {
return (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String]
}
For a direct answer to your question, you could ask each string in your array for its thisString.dataUsingEncoding(_:)
and append the result to an NSMutableData
instance until you're all done.
let stringsData = NSMutableData()
for string in strings {
if let stringData = string.dataUsingEncoding(NSUTF16StringEncoding) {
stringsData.appendData(stringData)
} else {
NSLog("Uh oh, trouble!")
}
}
Of course this doesn't help you if you want to separate the strings later, so what we really need to know is how / in what environment do you intend to consume this data on the other end of your connection? If the other end uses Cocoa as well, consider just packaging it as a PLIST. Since NSString
, NSArray
, and NSData
are all property list types, you can just archive your NSArray
of NSString
instances directly:
let arrayAsPLISTData = NSKeyedArchiver.archivedDataWithRootObject(strings)
...then transfer the resulting NSData
instance to the Cocoa-aware destination and then:
if let newStrings: [String] = NSKeyedUnarchiver.unarchiveObjectWithData(arrayAsPLISTData) as? [String] {
// ... do something
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With