Unicode URL =无法初始化“Foundation.NSUrl”类型的实例:本机“initWithString:”

时间:2016-04-18 03:47:03

标签: xamarin xamarin.ios

我正在尝试在UIWebView中打开一个包含unicode字符的URL:

var jrURL = new NSURL("http://δπθ.gr");

结果:

Could not initialize an instance of the type 'Foundation.NSUrl': 
the native 'initWithString:' method returned nil.
It is possible to ignore this condition by setting
MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure to false.

https://Google.com之类的工作正常

2 个答案:

答案 0 :(得分:4)

var jrURL = new NSURL(new System.Uri("http://δπθ.gr").AbsoluteUri);

轻松! ( - :

答案 1 :(得分:3)

IDN域名如:

必须转换(基于punycode)才能与NSUrl一起使用:

IDN:https://en.wikipedia.org/wiki/Internationalized_domain_name

Punycode:https://en.wikipedia.org/wiki/Punycode

您可以使用System.Globalization.IdnMapping将您的域名转换为Punycode和 此命名空间/类可在Xamarin.iOSXamarin.Android中找到。

var idn = new System.Globalization.IdnMapping ();
var dotnetURI = new System.Uri ("http://δπθ.gr);
Console.WriteLine (dotnetURI.ToString());
NSUrl nsURL = new NSUrl (dotnetURI.Scheme, idn.GetAscii (dotnetURI.DnsSafeHost), dotnetURI.PathAndQuery);
Console.WriteLine (nsURL.ToString());
WebView.LoadRequest(new NSUrlRequest(nsURL));

MSDN IdnMapping.GetAsciihttps://msdn.microsoft.com/en-us/library/system.globalization.idnmapping.getascii(v=vs.110).aspx

注意: System.Uri.IdnHost处理punycode转换是.Net 4.6的一部分,目前在Xamarin的System命名空间中不可用

参考:https://msdn.microsoft.com/en-us/library/system.uri.idnhost(v=vs.110).aspx