将[UInt8]作为数据附加到alamofire

时间:2018-03-21 07:13:27

标签: swift http byte alamofire

我正在尝试使用alamofire将一些字节上传到服务器,我的代码如下:

let parameters: Parameters = ["data": data]
let headers: HTTPHeaders = ["Content-Type": "application/vnd.awallet-signed-orders-v0"]

    Alamofire.request(query, method: .put,
                      parameters: parameters,
                      encoding: JSONEncoding.default,
                      headers: headers).responseJSON { response in
        print("Request: \(String(describing: response.request))")   // original url request
        print("Response: \(String(describing: response.response))") // http url response
        print("Result: \(response.result)") // response serialization result

        if let json = response.result.value {
            let parsedJSON = try! JSON(parseJSON: (json as! String))
            callback(parsedJSON["orders"]["accepted"])
        }

        if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
            print("Data: \(utf8Text)") // original server data as UTF8 string
        }
    }
}

数据是[UInt8]但是这样做会使alamofire将字节转换为字符串,如果数组为[0,0]则变为" 0,0",这不是我想要的因为我希望它直接上传字节。

有没有办法在alamofire中这样做?

注意:我不想将其转换为十六进制字符串,因为效率不高

1 个答案:

答案 0 :(得分:0)

解决了,只需要使用upload方法并将字节转换为数据

var hexMessageData = signedOrders[0].message

let headers: HTTPHeaders = ["Content-Type": "application/vnd.awallet-signed-orders-v0"]

Alamofire.upload(Data(bytes: hexMessageData), to: query, method: .put, headers: headers).response { response in
   if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
            print("Data: \(utf8Text)") // original server data as UTF8 string
            callback(data.hexEncoded)
        }
    }