简体   繁体   中英

Swift URLSession prevent redirect

I have a client code for authentication to server ( server implemented so that on success I receive a Redirect url) and want to check whether the status code is 302 or not. However the request is automatically redirected and the response is 200. so the question is how to prevent auto-redirection?

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() 
    })

I think you'll have to assign a delegate to your URLSession . Upon redirection, the method URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler: will be called. Here, you can do your checks etc.

For more details, see the Apple documentation Life Cycle of a URL Session

Assign a delegate to the URLSession in your controller or class, and implement the function below. source here and ensure ULRSession is not a background one.

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)
  }
}

If you are using Alamofire this will work

 let delegate = Alamofire.SessionManager.default.delegate

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

            return nil
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM