Semyon Tikhonenko
Semyon Tikhonenko

Reputation: 4232

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?

Upvotes: 3

Views: 593

Answers (3)

Mostafa Sultan
Mostafa Sultan

Reputation: 2438

Updated Answer with Swift 5

let theURLString = "URL" // your url string

let validURLString = theURLString.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)

let url = URL(string: validURLString)

Upvotes: 0

Eric Aya
Eric Aya

Reputation: 70096

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.

Upvotes: 3

Fogmeister
Fogmeister

Reputation: 77621

The main reason for URLs failing as far as I have seen is because of invalid URL characters.

You can get around this with...

let theURLString = // your url string

let validURLString = theURLString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPathAllowedCharacterSet())

let url = NSURL(string: validURLString)

Without seeing the string that you're actually trying to use it's hard to tell what the problem is.

Upvotes: 4

Related Questions