Ufuk Köşker
Ufuk Köşker

Reputation: 1470

How Can I convert byte array to String in Swift

I have a json as below. I need to convert the image to a byte array and post it as a String.

I can convert the image to byte array but how can I convert it to String? I am getting an error while converting byte array to String.

Error:

"not a valid UTF-8 sequence"

JSON:

"photo1": "[255,216,255,224,0,16,74,70,73, ..... ,]"

Image Data to Byte Array:

func getArrayOfBytesFromImage(imageData:NSData) -> Array<UInt8> {

    // the number of elements:
    let count = imageData.length / MemoryLayout<Int8>.size

    // create array of appropriate length:
    var bytes = [UInt8](repeating: 0, count: count)

    // copy bytes into array
    imageData.getBytes(&bytes, length:count * MemoryLayout<Int8>.size)

    var byteArray:Array = Array<UInt8>()

    for i in 0 ..< count {
      byteArray.append(bytes[i])
    }
    
    return byteArray
}

Using getArrayOfBytesFromImage Function:

if let string = String(bytes: getArrayOfBytesFromImage(imageData: imageData), encoding: .utf8) {
        print(string)
    } else {
        print("not a valid UTF-8 sequence")
    }

Upvotes: 0

Views: 340

Answers (1)

Sweeper
Sweeper

Reputation: 270770

Those are not UTF-8 bytes, so don't say encoding: .utf8. Those bytes do not form a string, so you should not use String.init(bytes:encoding:). You should get the value of those bytes, and get their description one way or another (e.g. by string interpolation).

You don't even need a byte array here. Just go straight to strings, since that's what you're after.

let imageData = Data([1, 2, 3, 4, 5]) // for example
let string = "[\(imageData.map { "\($0)" }.joined(separator: ","))]"
print(string) // prints [1,2,3,4,5]

Upvotes: 1

Related Questions