I am making a call to an API where I want have status equal to final or in progress. Here is the call I am using:
let request = NSMutableURLRequest(url: NSURL(string: "https://sportspage-feeds.p.rapidapi.com/games?status=in%20progress||status=final")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
It works perfectly in Postman, but when trying it in my app it is crashing with this error:
Fatal error: Unexpectedly found nil while unwrapping an Optional value: file
Is there a different way to use or in Swift?
You have manually percent encoded the space, but you have not percent encoded the two pipe characters. As a result the initialiser for
NSURLfails, returningnil. Since you have force-unwrapped this value, your app then crashes.You can use the function
.addingPercentEncoding(withAllowedCharacters:)to percent encode a string appropriately and then create aURL.Both percent encoding a string and creating a
URLcan fail, so these operations return an optional. You should use conditional unwrapping rather than force unwrapping to avoid crashes if these operations fail.Many
NSclasses have bridged Swift equivalents includingURLRequestforNSURLRequestandURLforNSURL. Idiomatic Swift eschews the use of anNSclass when a Swift equivalent exists.Use something like
As Matt pointed out in a comment, the correct way to construct a URL in iOS is to use
URLComponents. This allows you to specify each component of the URL independently and not worry about things like manual percent encoding.The use of
URLComponentsis particularly important where you collect input from the user and they could attempt to manipulate the resulting URL string.