在我努力为在 Xamarin Forms 中使用 HttpClient (SendAsync) 上传视频创建进度指示器时,我现在不得不寻求帮助。
上传本身和所有其他 API 调用都可以正常工作,但是当我尝试创建自定义HttpContent
来跟踪上传进度时,该项目甚至不会再构建。
错误 MT3001:无法 AOT 程序集 '[...].iOS/obj/iPhone/Debug/build-iphone7.2-10.1.1/mtouch-cache/Build/theproject.dll' (MT3001) (theproject.iOS )
使用 StreamContent 或 ByteArrayContent 代替项目构建,但我无法让它跟踪进度。
一段代码(这是最小的例子):
public class ProgressableContent : HttpContent
{
private const int defaultBufferSize = 4096;
private Stream content;
private int progress;
public ProgressableContent(Stream content)
{
this.content = content;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return Task.Run(async () =>
{
var buffer = new byte[defaultBufferSize];
var size = content.Length;
var uploaded = 0;
using (content) while (true)
{
var length = content.Read(buffer, 0, buffer.Length);
if (length <= 0) break;
uploaded += length;
progress = (int)((float)uploaded / size * 100);
await stream.WriteAsync(buffer, 0, length);
}
});
}
protected override bool TryComputeLength(out long length)
{
length = content.Length;
return true;
}
}
我通过将我的字节转换为流来使用它,希望是正确的:
//... building httpMessage.
httpMessage.Content = new ProgressableContent(await byteArrayContent.ReadAsStreamAsync());
//...
var response = await _httpClient.SendAsync(httpMessage, Cancellation.Token);
//...
问题:我是否以某种方式导致了错误?有一个更好的方法吗?
用 Xamarin.iOS 标记这个也是因为 monotouch 抱怨。