Search code examples
iosjsonswiftxcodealamofire

Response byte array from json


How can I response byte array from the server and convert it to image. This my code enter image description here

Alamofire.request(mainUrl, method:.post , parameters: paramstring , encoding: JSONEncoding.default, headers: nil).responseJSON { response in
        if let data = response.data
        {
            switch response.result
            {
            case.failure(let error):
            print(error)
            case.success(let value):
                let json = JSON(value)
                guard let dataarr = json["my_profile"].arrayObject as? [String] else {return}
                let image = dataarr[0]
                let mydata = image.data(using: String.Encoding.utf8)! as NSData
                print(mydata)
                let mybase64 = mydata.base64EncodedData(options: NSData.Base64EncodingOptions.endLineWithLineFeed)
                print(mybase64)
                self.MainView.avatarImageView.image = UIImage(data: mybase64)

            }
        }

as you can see , its not byte array , and it continue to 1000 rows enter image description here


Solution

  • Your data is not Base64-encoded. It's hex encoded. You need to hex-decode it, not use base64EncodedData.

    First, you need to drop the first two characters (\x):

    let hex = dataarr[0].dropFirst(2)
    

    Then you need a method to convert hex to Data. There are many ways. Here's one:

    extension Data {
        init?<S: StringProtocol>(hexString: S) {
            guard hexString.count % 2 == 0 else { return nil }  // Must be even number of letters
    
            var bytes: [UInt8] = []
    
            var index = hexString.startIndex
            while index != hexString.endIndex {
                let secondIndex = hexString.index(after: index)
                let hexValue = hexString[index...secondIndex]
                guard let byte = UInt8(hexValue, radix: 16) else { return nil } // Unexpected character
                bytes.append(byte)
                index = hexString.index(after: secondIndex)
            }
            self.init(bytes)
        }
    }
    

    With that, decode it:

    if let data = Data(hexString: hex),
       let image = UIImage(data: data) {
           // ... use image
    }