I'm trying to parse URLs that may not have a scheme specified. In that case, I want it to assume http, so I set the scheme strategy to .defaultValue("http"). However, when parsing a URL without a scheme, it fails with the following error:
error: Error Domain=NSCocoaErrorDomain Code=2048 "Cannot parse example.com. String should adhere to the preferred format of the locale, such as https://user:password@www.example.com/path?color=red#name."
If I prefix the URL string with "http://", it works fine.
I also tried setting the default value to "http:" and "http://" with the same result.
Here is the code I'm using to test this:
import Foundation
do {
let url = try URL(
"example.com", // this fails but "http://example.com" works
strategy: .url
.scheme(.defaultValue("http"))
.port(.defaultValue(8080))
.path(.defaultValue("/"))
)
print("parsed: \(url)")
} catch let error {
print("error: \(error)")
}
Is this a bug, or have I misunderstood the default value strategy?
Thanks!
I think this is expected behaviour. Consider the first snippet on this page of the docs. The default scheme applies in the last case (//example.com/path?key5=value5) but not in the first case (example.com?key1=value1).
Having said that, your overall goal seems reasonable enough and so I think it’d be reasonable for you to file an enhancement request for a way to make this work.
Please post your bug number, just for the record.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"