gpt4 book ai didi

Swift URLSession 防止重定向

转载 作者:行者123 更新时间:2023-11-30 11:38:28 38 4
gpt4 key购买 nike

我有一个用于对服务器进行身份验证的客户端代码(已实现服务器,以便在成功时我收到重定向网址),并且想要检查状态代码是否为 302。但是请求会自动重定向,响应结果是200。那么问题是如何防止自动重定向?

let params = ["username":LoginField.text, "password":PassField.text] as! Dictionary<String, String>

var request = URLRequest(url: URL(string: NSLocalizedString("url_login", comment: ""))!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 302 {

result=1;

}else{
result=0;
}
}
semaphore.signal()
})

最佳答案

将委托(delegate)分配给 Controller 或类中的 URLSession,并实现以下功能。来源here并确保 ULRSession 不是后台 session 。

extension YourControllerOrClass: NSURLSessionTaskDelegate {
func URLSession(session: NSURLSession,
task: NSURLSessionTask,
willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest,
completionHandler: (NSURLRequest!) -> Void) {
// Stops the redirection, and returns (internally) the response body.
completionHandler(nil)
}
}

关于Swift URLSession 防止重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49477437/

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