Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert String Array to NSData, NSData to String Array?

Tags:

swift

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..
like image 419
ketancho Avatar asked Oct 29 '15 16:10

ketancho


2 Answers

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]
}
like image 150
AntScript Avatar answered Oct 09 '22 13:10

AntScript


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

}
like image 12
Joshua Nozzi Avatar answered Oct 09 '22 12:10

Joshua Nozzi