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

问题描述 投票:0回答:1

我正在调用一个 API,我希望

status
等于
final
in 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 中完美运行,但是当在我的应用程序中尝试它时,它因以下错误而崩溃:

致命错误:解包可选值时意外发现 nil:文件

在 Swift 中是否有其他使用

or
的方法?

ios swift nsurlrequest
1个回答
1
投票

您已手动对空格进行百分比编码,但尚未对两个管道字符进行百分比编码。 因此

NSURL
的初始化程序失败,返回
nil
。 由于您已强制解开该值,因此您的应用程序会崩溃。

您可以使用函数

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

对字符串进行百分比编码和创建

URL
都可能失败,因此这些操作返回一个可选值。 您应该使用条件展开而不是强制展开,以避免这些操作失败时发生崩溃。

许多

NS
类都桥接了 Swift 等效项,包括
URLRequest
NSURLRequest
URL
NSURL
。 当存在 Swift 等效项时,惯用的 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 的每个组成部分,而不必担心手动百分比编码等问题。

当您收集用户的输入并且他们可能会尝试操纵生成的 URL 字符串时,

URLComponents
的使用尤其重要。

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)
    ...
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.