AlexP
AlexP

Reputation: 459

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

Upvotes: 2

Views: 4426

Answers (3)

Shivang Pandey
Shivang Pandey

Reputation: 188

If you are using Alamofire this will work

 let delegate = Alamofire.SessionManager.default.delegate

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

            return nil
        }

Upvotes: -1

Morlo Mbakop
Morlo Mbakop

Reputation: 3756

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

Upvotes: 2

Andreas Oetjen
Andreas Oetjen

Reputation: 10199

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

Upvotes: 0

Related Questions