来自json的响应字节数组

时间:2018-06-13 11:43:52

标签: ios json swift xcode alamofire

如何从服务器响应字节数组并将其转换为图像。这是我的代码 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)

            }
        }

如你所见,它不是字节数组,它继续1000行 enter image description here

2 个答案:

答案 0 :(得分:1)

您的数据不是Base64编码的。它是十六进制编码的。您需要对其进行十六进制解码,而不是使用base64EncodedData

首先,您需要删除前两个字符(\x):

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

然后你需要一个方法将十六进制转换为数据。有很多方法。这是一个:

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

用它解码它:

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

答案 1 :(得分: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)

使用

if let mydata : Data = Data(base64Encoded: image, options: .ignoreUnknownCharacters) {
   DispatchQueue.main.async {
       self.MainView.avatarImageView.image = UIImage(data: mydata)
    }

}