Swift URLSession阻止重定向

时间:2018-03-25 15:22:06

标签: swift urlsession

我有一个客户端代码用于对服务器进行身份验证(服务器已实现,因此成功时我会收到一个Redirect 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() 
    })

3 个答案:

答案 0 :(得分:0)

我认为您必须为您的URLSession分配一名代表。重定向后,将调用方法URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:。在这里,您可以进行检查等。

有关详细信息,请参阅Apple文档Life Cycle of a URL Session

答案 1 :(得分:0)

将委托分配给控制器或类中的URLSession,并实现以下功能。来源here并确保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)
  }
}

答案 2 :(得分:0)

如果您使用的是Alamofire,则可以使用

 let delegate = Alamofire.SessionManager.default.delegate

        delegate.taskWillPerformHTTPRedirection = { (session, task, response, request) -> URLRequest? in

            return nil
        }