Skip to content

Instantly share code, notes, and snippets.

@mgersty
Last active April 5, 2022 02:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgersty/b565ba4c9e9422637f15f52a5317f07e to your computer and use it in GitHub Desktop.
Save mgersty/b565ba4c9e9422637f15f52a5317f07e to your computer and use it in GitHub Desktop.
Swift code demonstrating the capture of a 302 redirect via delegates
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
class DelegateToHandle302:NSObject, URLSessionTaskDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
print(response.description)
PlaygroundPage.current.finishExecution()
}
}
//set configurartions
let urlString = "[insert URL String]"
let config = URLSessionConfiguration.default
let url = URL(string: urlString)
//set delegate value equal to SessionDelegate to handle 302 redirect
let delegate = DelegateToHandle302()
//establish url session
let session = URLSession(configuration: config, delegate: delegate, delegateQueue: nil)
//set task with url
let dataTask = session.dataTask(with: url!)
//init call
dataTask.resume()
@shfyr
Copy link

shfyr commented Feb 20, 2020

Thank you !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment