简体   繁体   中英

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")
    }

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 (eg 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM