The URL(string:)
initializer returns an optional since the parsing of the string may fail. In that case, nil
is returned. That's exactly what's happening here since the string you are providing is not a valid URL: there are several characters in the query that are not allowed there and need to be replaced: {
as %7B
, "
as %22
, space as %20
and }
as %7D
.
So the initializer returns nil
. Next thing you do is force unwrap via the !
operator. But force-unwrapping a nil
is illegal and is why you get the crash.
If you want to create an URL, please look into the URLComponents class which does all the necessary escaping for you so you don't need to care about it. The queryItems
property is of particular interest for you, it's an array of URLQueryItem.