I need to get the redirect URL, but prevent the redirect in Swift. From other Apple posts and documents, I understand that I have to implement the URLSession(session:, task:, willPerformHTTPRedirection response:, request:, completionHandler:) delegate URLSession(session:, task:, willPerformHTTPRedirection response:, request:, completionHandler:) and return nil through closing completion. But I canโt find examples in quick and donโt know how to do it right. The following code reproduces my problem on the playground: the delegate does not seem to be executing.
import Foundation import XCPlayground XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true) class MySession: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate {
Please be careful, I'm new. Thank you in advance for your help!
UPDATE: Thanks a lot thanks to @nate, I got it to work. The basic idea is that in order for the delegate to be called, you need to pass the delegate class to the NSURLSession() initializer, and not use NSURLSession.sharedSession() . Passing nil as the delegate gives the usual behavior (with redirection). Here is the working version of the code:
import Foundation import XCPlayground XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true) class MySession: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate { // to prevent redirection func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest!) -> Void) { completionHandler(nil) } // fetch data from URL with NSURLSession class func getDataFromServerWithSuccess(myURL: String, noRedirect: Bool, success: (response: String!) -> Void) { var myDelegate: MySession? = nil if noRedirect { myDelegate = MySession() } let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: myDelegate, delegateQueue: nil) let loadDataTask = session.dataTaskWithURL(NSURL(string: myURL)!) { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in // OMITTING ERROR CHECKING FOR BREVITY success(response: NSString(data: data!, encoding: NSASCIIStringEncoding) as String) } loadDataTask.resume() } // extract data from redirect class func getRedirectionInfo(url: String) { getDataFromServerWithSuccess(url, noRedirect: true) {(data) -> Void in if let html = data { if html.rangeOfString("<html>\n<head><title>Bitly</title>", options: .RegularExpressionSearch) != nil { println("success: redirection was prevented") } else { println("failure: redirection went through") } } } } } MySession.getRedirectionInfo("http://bit.ly/filmenczer")