URL(string:) Stopped Returning nil for Garbage in iOS 17. Your Validation Still Trusts It.

NativeFirst Team 9 min read
A door standing half open in a dark room with red light spilling through the gap

The profile screen had a “Website” field. One user’s website, according to my database, was ask%20me%20in%20person.

There was a nice blue link on their profile. Tapping it did nothing. Not an error, not a crash, just a link with the confidence of a URL and the destination of a brick wall.

I had validation on that field. I’d written it myself, years ago, and it was four lines long. It had quietly stopped validating anything, and the thing that broke it was me updating Xcode.


The bouncer who lets everyone in

Here’s the validation. You’ve written it too. Everybody has.

func isValidWebsite(_ input: String) -> Bool {
    guard let _ = URL(string: input) else { return false }
    return true
}

For most of iOS history, this sort of worked. URL(string:) returned nil when the string contained characters that aren’t legal in a URL, and the most common illegal character by far is the space. So “ask me in person” came back nil, the form showed a red error, and I felt like a responsible engineer.

Then iOS 17 changed the rules:

URL(string: "ask me in person")
// iOS 16 and earlier:  nil
// iOS 17 and later:    ask%20me%20in%20person

URL(string:) no longer rejects invalid characters. It percent-encodes them and hands you a URL. Spaces, accents, emoji, the lot. As far as I can tell, the only string that still reliably comes back nil is the empty one.

My bouncer didn’t get fired. He just started waving everyone through.


What actually changed

Apple moved URL to a new parser. Before iOS 17, URL followed the older RFC 1738 and 1808 rules, while URLComponents followed the newer RFC 3986. Two types, same framework, two different opinions about what a URL is. That was a real source of bugs, and unifying them was the right call.

As part of that cleanup, URL(string:) picked up a new default: if the string has invalid characters, encode them instead of failing. For the common case, this is a gift:

URL(string: "https://example.com/files/Q3 report.pdf")
// iOS 16: nil  (and a crash, if someone force-unwrapped it)
// iOS 17: https://example.com/files/Q3%20report.pdf

A whole category of “why is my URL nil” Stack Overflow questions went away overnight. Honestly, good.

But the same leniency means the initializer’s return value stopped carrying information. nil used to mean “this isn’t a URL.” Now a non-nil result means “this was a non-empty string.”


Why it showed up when you updated Xcode

This one cost me an afternoon. The new behavior applies to apps linked against the iOS 17 SDK or later. It’s tied to what you built with, not just what the phone runs.

So the timeline looked like this. My old build, running on iOS 17 devices, still rejected spaces. I shipped a point release built with a newer Xcode, changed nothing in the form, and the validation went soft for everyone on iOS 17 at once. No diff touched that file. Git blame pointed at code from years earlier.

The only early warning was a unit test that started failing:

XCTAssertNil(URL(string: "has a space"))  // failed after the Xcode update

I’m slightly ashamed to say what happened to that test. Someone “fixed” it by deleting it. The someone was me.

If you maintain an older app, it’s worth searching your test history for exactly this. A deleted XCTAssertNil(URL(string: is a fossil of this bug.


It was never a validator anyway

Here’s the uncomfortable part. Even on iOS 16, that check was terrible.

URL(string: "hello")                 // a URL, on every iOS version
URL(string: "example.com")           // a URL with no scheme and no host
URL(string: "javascript:alert(1)")   // a URL, and not one you want
URL(string: "http://")               // a URL to nowhere

All of those were always non-nil. A bare word is a perfectly legal relative URL. example.com parses as a path, not a host, which is why UIApplication.shared.open shrugs at it.

URL(string:) answers “can this be parsed as a URL reference?” It never answered “is this a web address a human can visit?” The space check just happened to catch the most common junk, so the gap stayed hidden. iOS 17 removed the coincidence.

It’s the same family as interpolating an optional and getting the literal text “Optional(42)”: the type system says you have a valid value, and the value is nonsense.


Fix 1: validate the parts, not the parse

If you want a web link, say so. Check for the things a web link has.

func webURL(from input: String) -> URL? {
    let trimmed = input.trimmingCharacters(in: .whitespacesAndNewlines)
    guard
        let url = URL(string: trimmed),
        let scheme = url.scheme?.lowercased(),
        ["http", "https"].contains(scheme),
        let host = url.host(),
        !host.isEmpty
    else { return nil }
    return url
}

Scheme allowlist, non-empty host. That’s the whole trick. "ask me in person" has no scheme. "javascript:alert(1)" has the wrong one. "http://" has no host. All rejected.

Notice I kept the lenient URL(string:) here on purpose. A user who pastes https://example.com/my file.pdf gave me a real address with a real space in it, and the new behavior turns that into something that works. For human input, leniency plus structural checks is the combination you want.

If you want to be friendlier still, prepend https:// when the input has no scheme, then run the same check. Just do it before validating, not instead of validating.


Fix 2: ask for the old strictness when garbage means a bug

Sometimes the string doesn’t come from a human. It comes from your API, a config file, a deep link payload. There, a space in a URL isn’t a typo to forgive. It’s a sign something upstream is broken, and you’d like to know.

iOS 17 added an initializer for exactly that:

// Returns nil for invalid characters, like the old days.
let url = URL(string: payload.avatarURL, encodingInvalidCharacters: false)

Lenient for people, strict for machines. I now treat the choice between the two initializers as a decision I make every time, the same way I think about try? versus try.

One note on what the lenient version won’t do: it fixes invalid characters, not misleading ones. A + or & inside a query value is perfectly legal, so it’s left alone, and your server will still read that + as a space. I wrote about that one in URLComponents and the plus sign. Automatic encoding is not the same as correct encoding.


Fix 3: for free text, use a detector

If the job is “does this blob of text contain a link,” don’t parse at all. NSDataDetector has been doing this for years and has better instincts than a hand-rolled check.

func isSingleLink(_ input: String) -> Bool {
    let types = NSTextCheckingResult.CheckingType.link.rawValue
    guard let detector = try? NSDataDetector(types: types) else { return false }
    let range = NSRange(input.startIndex..., in: input)
    let matches = detector.matches(in: input, range: range)
    return matches.count == 1 && matches[0].range == range
}

It understands example.com without a scheme, which is how actual people type web addresses. Note the NSRange(_:in:) conversion, by the way. Building that range from input.count is its own bug.


Pin it down with a test

The reason this slipped through is that my only test asserted on URL(string:) itself, which is Apple’s behavior, not mine. Test your function instead:

import Testing

@Test(arguments: [
    "ask me in person", "hello", "example.com",
    "http://", "javascript:alert(1)", "   ", ""
])
func rejectsThingsThatAreNotWebLinks(_ input: String) {
    #expect(webURL(from: input) == nil)
}

@Test func acceptsARealLinkWithASpace() {
    let url = webURL(from: " https://example.com/my file.pdf ")
    #expect(url?.absoluteString == "https://example.com/my%20file.pdf")
}

I haven’t run this exact file against every OS version, so treat the second test as the one to watch. If Apple tweaks the parser again, that’s where you’ll hear about it first, and hearing about it from a test beats hearing about it from a profile page.

Then grep the project for URL(string: sitting inside a guard or an if let. Each hit is either a parse (fine) or a validation in disguise (not fine). In my codebase it was eleven hits and three disguises, including one that decided whether to show a “Visit website” button.

This is also a good place to hand the grep results to an AI assistant and ask which ones are acting as validation. That kind of “read forty call sites and classify them” chore is covered in the Debugging with AI lesson, and it’s faster than squinting at each one yourself.


The takeaway

URL has gotten more forgiving two releases in a row: iOS 16 gave us a path() that percent-encodes by default, and iOS 17 gave us a URL(string:) that encodes instead of refusing. Both changes are reasonable. Both broke code that leaned on the old behavior without ever saying so.

A failable initializer feels like a validator because it can say no. But it only says no to what it can’t handle, and that’s a much shorter list than what your app can’t handle.

Somewhere out there is a user whose website is still “ask me in person.” Fair enough. I should have.

Share this post

Share on X LinkedIn

Comments

Leave a comment

0/1000

N

NativeFirst Team

Editorial

The NativeFirst team — engineers and designers building native Apple apps and writing the courses we wish we had when we started.