What is the C# equivalent of Swift's URL struct in Xamarin.iOS?

Viewed 249

I am using Xamarin.iOS and I am working with NSAttributeString.

I need to know if a link attribute contains an URL. I found a Swift code to do that: if let url = value as? URL but I don't know what C# class represent 'URL'.

From what I can understand URL and NSUrl are different, so I cannot use the latter. It there a naming pattern for those Swift structures?

2 Answers

URL is just an "overlay" of NSURL and since Xamarin.iOS is directly using Objective-C APIs, you should just use the NSURL reference type directly.

  • "Swift-based" URL:

An object representing the location of a resource that bridges to URL; use NSURL when you need reference semantics or other Foundation-specific behavior.

  • NSURL:

The Swift overlay to the Foundation framework provides the URL structure, which bridges to the NSURL class."

re: https://developer.apple.com/documentation/foundation/nsurl

The URL value type offers the same functionality as the NSURL reference type, and the two can be used interchangeably in Swift code that interacts with Objective-C APIs. This behavior is similar to how Swift bridges standard string, numeric, and collection types to their corresponding Foundation classes."

Use Uri class and try this approach:

bool isUriCorrect = Uri.IsWellFormedUriString("https://www.stackoverflow.com", UriKind.Absolute);

Advised method IsWellFormedUriString() indicates whether the string is well-formed by attempting to construct a URI with the string and ensures that the string does not require further escaping.

Related