NSData to String in Swift Issues
let testBytes : [UInt8] = [0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64]func bytes2String(array:[UInt8]) -> String { return String(data: NSData(bytes: array, length: array.count), encoding: NSUTF8StringEncoding) ?? ""}
Xcode 8.2 • Swift 3.0.2
func bytes2String(_ array: [UInt8]) -> String { return String(data: Data(bytes: array, count: array.count), encoding: .utf8) ?? ""}
Testing:
bytes2String(testBytes) // "Hello World"
Use valid UTF8 characters!
// Playground - noun: a place where people can playimport UIKitvar str = "Hello, playground"import Foundation//: # NSData to String Conversion Playground//: ### Step 1//: The first step is to take an array of bytes and conver them into a NSData object. The bytes are as follows:// Hello Worldvar testBytes : [UInt8] = [0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64]//: ### Step 2//: Convert the byte array into an **NSData** Objectvar immutableData = NSData(bytes: testBytes, length: testBytes.count)//: ### Step 3//: Attempt to convert the **NSData** object into a string so it can be sent around as ascii. This for some reason seems to be failing, however.var convertedString = NSString(data: immutableData, encoding: NSUTF8StringEncoding)println("String = \(convertedString)")
Your output will be:"String = Optional(Hello World)"
If you just want hex values in string:
I just want a string of the hex values. I guess this is trying to decode as actual ascii! Duh!! – Jeef Mar 4 at 23:29
The easiest way to do this is just use Swifts built in string interpolation.
let myHexString = "\(myNSDataObject)"
This will give you a string of hex with spaces between each two characters and surrounded by square brackets. Like this:
<a0 ff 21 4a>
You could format it with using the built in string methods:
myHexString.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>")).stringByReplacingOccurrencesOfString(" ", withString: "")
You will have then have a string containing: a0ff214a