Search code examples
swiftnsurl

How to get an error info after NSURL constructor returns nil?


let url = NSURL(string: "http://example.com")

As I understand NSURL returns nil, when its construction failed.

How can I get the fail error info?


Solution

  • Unfortunately, NSURL won't tell you why the URL creation failed.

    From the Xcode popup when doing ALT+CLICK on NSURL:

    Handling Object Creation Failure
    The NSURL class fails to create a new NSURL object if the path being passed is not well formed; the path must comply with RFC 2396. Examples of cases that will not succeed are strings containing space characters and high-bit characters. If creating an NSURL object fails, the creation methods return nil, which you must be prepared to handle.

    So NSURL will just return nil if it fails, without giving any further details. Handle this as usual with Optional binding, Optional chaining, guard, or any other known technique to safely unwrap optionals, and also follow Fogmeister's advice and encode the URL string before usage.