我有一个用于身份验证的客户端代码(服务器已实现,以便成功,我会收到重定向URL(,并希望检查状态代码是否为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()
})
将委托给您的控制器或类中的urlsession,并在下面实现功能。在这里来源并确保Ulrsession不是背景。
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)
}
}
我认为您必须将委托给URLSession
。重定向后,将调用URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:
方法。在这里,您可以进行检查等。
有关更多详细信息,请参见Apple文档的生命周期
如果您使用的是Alamofire,则可以正常工作
let delegate = Alamofire.SessionManager.default.delegate
delegate.taskWillPerformHTTPRedirection = { (session, task, response, request) -> URLRequest? in
return nil
}