How can I serve a byte array as a response body?
garie opened this issue · 1 comments
I am trying to mock a call to get an image from our image service. I have so far been unable to successfully provide an image to my app.
This is the service code to serve up the image (C#):
private async Task<dynamic> GetThumbnail(dynamic parameters, CancellationToken ct)
{
string token = Request.Query["token"].ToString();
byte[] thumbnail = await _service.GetThumbnail(token, ct);
return thumbnail == null
? HttpStatusCode.NotFound
: new ByteArrayResponse(thumbnail, "image/jpeg");
}
public ByteArrayResponse(byte[] body, string contentType)
{
ContentType = contentType;
Contents = stream =>
{
using (var writer = new BinaryWriter(stream))
{
writer.Write(body);
}
};
}
This is the pact I have written to mock the image response:
mockService
.uponReceiving("a request for getting a thumbnail for image \(imageId)")
.withRequest(method: .GET, path: req, query: ["token": token])
.willRespondWith(status: 200,
headers: ["Content-Type": "image/jpeg",
"Transfer-Encoding": "chunked"],
body: image)
I have so far been unable to get the body to be correct. In my code, I am calling UIImage(data: body)
, which works fine when hitting the actual service, but returns null anytime I have used this pact.
I am using Alamofire for my requests.
I have tried the following for the body:
- crashes with "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Foundation._SwiftNSData)'"
let image = UIImageJPEGRepresentation(myUIImage, 1.0)!
- does not create a UIImage
let image = UIImageJPEGRepresentation(myUIImage, 1.0)!.base64EncodedString()
- does not create a UIImage
let image = NSKeyedUnarchiver.unarchiveObject(with: UIImageJPEGRepresentation(myUIImage, 1.0)!)
- does not create a UIImage
let image = getArrayOfBytesFromImage(imageData: UIImageJPEGRepresentation(myUIImage, 1.0)!)
func getArrayOfBytesFromImage(imageData: Data) -> NSMutableArray {
let count = imageData.count / MemoryLayout<UInt8>.size
var bytes = [UInt8](repeating: 0, count: count)
imageData.copyBytes(to: &bytes, count:count * MemoryLayout<UInt8>.size)
let byteArray:NSMutableArray = NSMutableArray()
for i in 0..<count {
byteArray.add(NSNumber(value: bytes[i]))
}
return byteArray
}
I am not sure what else to try to serve up the image. Any suggestions?
@garie I haven't tried to do this before, but my initial thought would be to try and read an image file from disk and use it as the body, then you don't have to deal with trying to convert the uiimage to the correct format.