7

I am trying to open a url in UIWebView that contains unicode characters:

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

Results in:

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.

Ones like https://Google.com work fine

2 Answers 2

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

Easy! (-:

5

IDN Domain names like:

Have to be converted (punycode based) in order to be use with NSUrl:

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

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

You can use System.Globalization.IdnMapping to convert your domain names to Punycode and this Namespace/Class is available in Xamarin.iOS and Xamarin.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.GetAscii: https://msdn.microsoft.com/en-us/library/system.globalization.idnmapping.getascii(v=vs.110).aspx

Note: System.Uri.IdnHost which handling punycode conversions is a part of .Net 4.6 and is not currently available in the Xamarin's System namespace

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

3
  • IS there any native iOS function?
    – user6217862
    Apr 18, 2016 at 3:56
  • Surprising there is not, Safari/Webkit has this function builtin but it is not available via any SDK that I know if, Here is a punycode converter written in ObjC that you could wrap into a static library and bind it with sharpie (github.com/wordpress-mobile/NSURL-IDN) but using the .Net based one is "easier" Apr 18, 2016 at 4:02
  • Wow, rare case when .NET worked better on Xamarin the Native SDK. Apr 9, 2019 at 15:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy