The URL Initialization Trap: Debugging a Simple Mistake That Cost Hours
Check the initializer twice
We all have those days when a simple task turns into an unexpected debugging marathon. Last week, I wasn’t feeling great and lost focus while working on something that should have taken just a few minutes—adding an external URL view in SwiftUI. Sounds simple, right? Well, what followed was hours of frustration and confusion. Here’s what happened.
The Unexpected WKWebView Error
I had a wrapper around WKWebView
that accepted a URL
. But when I ran the code in the iOS Simulator, I was greeted with this error:
WKWebView Could not create a sandbox extension for '/'
At first, this didn’t make sense. Why would WKWebView
fail to load a perfectly valid URL? Just to isolate the issue, I switched to using SFSafariViewController
, thinking it would handle the URL differently.
A Different Error in SFSafariViewController
Instead of the sandbox error, I now saw:
The specified URL has an unsupported scheme. Only HTTP and HTTPS URLs are supported.
Wait… what? My URL did have https
, so what was going on?
The Debugging Journey
I started investigating the URL itself:
po url
To my surprise, it printed a file URL:
file:///
I then checked the scheme:
print(url.scheme)
And sure enough, it was file://
instead of https://
.
The Culprit: Deprecated URL Initialization
After digging further, I realized my mistake—I had used the wrong initializer for URL
. Instead of the standard:
let url = URL(string: "https://example.com")
I had mistakenly used the deprecated initializer:
let url = URL("https://example.com") // Deprecated!
This initializer is meant for file paths, not web URLs. Since the string didn’t point to a real file, it defaulted to file:///
, causing all the confusion.
Lessons Learned
1. Be mindful of deprecated initializers. URL(_:)
is meant for file paths, not general URLs. Always use URL(string:_)
for web addresses.
2. Simulator errors can be misleading
3. Double-check your URL scheme. If something doesn’t load, print(url.scheme)
early in debugging.
This was one of those bugs that, in hindsight, seems obvious—but at the moment, it was incredibly frustrating. Hopefully, this helps others avoid the same mistake!
Have you ever lost hours to a tiny mistake like this? Let’s commiserate in the comments! 😅