或者参数化API调用在Swift中崩溃



我正在对API进行调用,其中我希望status等于finalin progress。这是我正在使用的电话:

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)

它在Postman中运行得很好,但当在我的应用程序中尝试时,它会崩溃,并出现以下错误:

Fatal error: Unexpectedly found nil while unwrapping an Optional value: file

在Swift中使用or有不同的方法吗?

您已经手动对空间进行了百分比编码,但尚未对两个管道字符进行百分比编码。因此,NSURL的初始化程序失败,返回nil。由于您已强制打开此值,因此您的应用程序将崩溃。

您可以使用函数.addingPercentEncoding(withAllowedCharacters:)对字符串进行适当的百分比编码,然后创建一个URL

对字符串进行百分比编码和创建URL都可能失败,因此这些操作返回一个可选的。如果这些操作失败,您应该使用条件展开而不是强制展开,以避免崩溃。

许多NS类已经桥接了Swift等价物,包括用于NSURLRequestURLRequest和用于NSURLURL。当存在Swift等价类时,Idiomatic Swift避免使用NS类。

使用类似的东西

if let urlStr = "https://sportspage-feeds.p.rapidapi.com/games?status=in progress||status=final".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(urlStr) {
let request = URLRequest(url, timeoutInterval: 10)
...
}   

正如Matt在评论中指出的那样,在iOS中构建URL的正确方法是使用URLComponents。这允许您独立指定URL的每个组件,而不必担心手动百分比编码之类的问题。

URLComponents的使用尤其重要,因为您可以从用户那里收集输入,并且他们可以尝试操作生成的URL字符串。

var components = URLComponents()
components.scheme = "https"
components.host = "sportspage-feeds.p.rapidapi.com"
components.path = "/games"
components.queryItems = [(URLQueryItem(name:"status", value:"in progress||status=final"))]
if let url = components.url {
let request = URLRequest(url, timeoutInterval: 10)
...
}

最新更新