I need to fetch a redirecting URL but prevent redirection in Swift. From other posts and Apple docs I understand I must implement the delegate method URLS
You have two things standing in your way with your current implementation.
You never set the delegate property on the NSURLSession
instance that you're using to make the request. Without the delegate property set, your delegate methods won't ever be called. Instead of getting NSURLSession.sharedSession()
, look at the NSURLSession(configuration:delegate:delegateQueue:)
initializer. The first and last parameters can be NSURLSessionConfiguration.defaultSessionConfiguration()
and nil
, respectively, see below for more about the delegate.
Note that when you use the variant of
session.dataTaskWithURL
that has a completion handler, delegate methods that handle response and data delivery will be ignored, but authentication and redirection handlers are still used.
You'll have to refactor somewhat to use MySession
as a delegate, since you're using class methods to make the request. You need an instance to use as the session's delegate.
I took a short and incomplete route to having the delegate pick up on the redirect with this alternate code—you'll need to refactor as in #3 to make sure you can still call your callback:
class func getDataFromServerWithSuccess(myURL: String, success: (response: String!) -> Void) {
let delegate = MySession()
var session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: delegate, delegateQueue: nil)
let task = session.dataTaskWithURL(NSURL(string: myURL)!) {
// ...
}
task.resume()
}
Hope that helps!