gpt4 book ai didi

swift - 如何扩展 URLRequest

转载 作者:行者123 更新时间:2023-11-28 10:48:44 25 4
gpt4 key购买 nike

尝试编写可维护的、干净的代码的结果:

func fetchNumbersFromServer(completion: @escaping (NumbersResult) -> Void) {
let urlString = "https://some-site.com/some-file"
var request = URLRequest(url: URL.init(string: urlString)!)
// I want to configure the request, yet make the code extenda
request = URLRequest.configure(request: request)
// create URLSession configuration, delegate and session
...
session.dataTask(with: request) { (data, response, error) -> Void in
// handle response
}.resume()
}

extension URLRequest {

static func configure(request: URLRequest) -> URLRequest {
// request in must be made mutable
var request = request
request.setValue("some user agent", forHTTPHeaderField: "User-Agent")
request.timeoutInterval = 10

return request
}

}

通过使用类型方法,这可以修改请求。然而,这对我来说感觉很尴尬,所以我想知道是否有更好(或更有效)的方法来完成“配置”URLRequest。

最佳答案

您可以只创建一个 URLRequest 自定义初始化程序并为参数设置一个默认值:

extension URLRequest {
init(_ url: URL, userAgent: String = "your default user agent", cachePolicy: CachePolicy = .useProtocolCachePolicy, timeInterval: TimeInterval = 60) {
self.init(url: url, cachePolicy: cachePolicy, timeoutInterval: timeInterval)
setValue(userAgent, forHTTPHeaderField: "User-Agent")
}
}

struct NumbersResult { }

func fetchNumbersFromServer(request: URLRequest, completion: @escaping (NumbersResult) -> ()) {
URLSession.shared.dataTask(with: request) { data, response, error in
// handle response
}.resume()
}

let url = URL(string: "https://www.google.com")!
let request = URLRequest(url) // you can also pass another userAgent, cachePolicy and timeInterval here if needed
fetchNumbersFromServer(request: request) { numbers in

}

关于swift - 如何扩展 URLRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47182754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com