C#-MonoTouch-UIDevice.CurrentDevice.Name-UTF8
作者:互联网
我们注意到在MonoTouch中使用UIDevice.CurrentDevice.Name时,UTF8字符不能正确显示.
如果您使用某些特殊字符(例如,按住iPad键盘上的撇号键),则显示为“ iPad 2 ??”. (对不起,不知道在Windows中显示这些字符的等效项)
是否有建议的解决方法来获取正确的文本?我们不介意自己转换为UTF8.我还尝试从UITextField进行模拟,并且效果很好-没有UTF8问题.
造成问题的原因是我们将文本发送到Web服务,并导致XML解析问题.
以下是XmlWriter代码(_parser.WriteRequest)的摘要:
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, new XmlWriterSettings
{
#if DEBUG
Indent = true,
#else
Indent = false, NewLineHandling = NewLineHandling.None,
#endif
OmitXmlDeclaration = true
}))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("REQUEST");
xmlWriter.WriteAttributeString("TYPE", "EXAMPLE");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
}
TextWriter是从以下位置传入的:
public Response MakeRequest(Request request)
{
var httpRequest = CreateRequest(request);
WriteRequest(httpRequest.GetRequestStream(), request);
using (var httpResponse = httpRequest.GetResponse() as HttpWebResponse)
{
using (var responseStream = httpResponse.GetResponseStream())
{
var response = new Response();
ReadResponse(response, responseStream);
return response;
}
}
}
private void WriteRequest(Stream requestStream, Request request)
{
if (request.Type == null)
{
throw new InvalidOperationException("Request Type was null!");
}
if (_logger.Enabled)
{
var builder = new StringBuilder();
using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture))
{
_parser.WriteRequest(writer, request);
}
_logger.Log("REQUEST: " + builder.ToString());
using (requestStream)
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(builder.ToString());
}
}
}
else
{
using (requestStream)
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
_parser.WriteRequest(writer, request);
}
}
}
}
_logger写入Console.WriteLine,在#if DEBUG模式下启用. Request只是具有属性的存储类,很容易与HttpWebRequest混淆.
我正在看 ??在XCode的控制台和MonoDevelop的控制台中.我还假设服务器也收到了奇怪的消息,因为出现错误.使用具有相同奇怪字符的UITextField.Text代替设备描述,可以正常工作,没有任何问题.这让我认为设备描述是罪魁祸首.
编辑:此修复它-
Encoding.UTF8.GetString(Encoding.ASCII.GetBytes(UIDevice.CurrentDevice.Name));
解决方法:
好吧,我想我知道问题所在.您正在创建一个StringWriter,它始终将其编码报告为UTF-16(除非您覆盖Encoding属性).然后,您从该StringWriter中获取字符串(它将以<?xml version =“ 1.0” encoding =“ UTF-16”?>开头)并将其写入到StreamWriter(默认为UTF-8)中.编码的混合导致了问题.
最简单的方法是更改代码,以将Stream直接传递给XmlWriter-如果确实需要,则传递给MemoryStream,或者只是requestStream.这样,XmlWriter可以声明它使用的是实际写入二进制数据时所使用的精确编码-您没有中间步骤来弄乱事情.
另外,您可以创建StringWriter的子类,该子类允许您指定编码.有关一些示例代码,请参见this answer.
标签:xamarin-ios,utf-8,c,net 来源: https://codeday.me/bug/20191101/1984261.html