0

I am sending a DataTask to some website and in URL I have redirection to localhost (https://...&redirect_uri=http://localhost...). Overall in that call I am getting about 5 redirections, where localhost is probably third and after that redirection localhost keeps in its URL important string that I want to take, so I decided to prevent redirections, when URL will start with localhost and its further specific URL:

extension MyClass: URLSessionTaskDelegate {
  func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
    if response.url?.absoluteString.hasPrefix("http://localhost/bar?code=") ?? false {
      completionHandler(nil)
    }
    completionHandler(request)
  }

and I set my URLSession object's delegate as that class:

  private var session: URLSession { URLSession(configuration: .default, delegate: self, delegateQueue: nil) } // `self` is MyClass

After sending request mentioned in the beginning of the question Xcode throws that error:

Task <UIID>.<1> finished with error [-1004] Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo={NSUnderlyingError=0x600000cc46f0 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo={_kCFStreamErrorCodeKey=61, _kCFStreamErrorDomainKey=1}}, NSErrorFailingURLStringKey=http://localhost/bar?code=[code], NSErrorFailingURLKey=http://localhost/bar?code=[code], _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=61, NSLocalizedDescription=Could not connect to the server.}

As You see, that delegate method isn't called (I've additionally checked that with breakpoints). I found that some other methods of that delegate doesn't fire when I am using closure on dataTask(with:), but it doesn't apply on redirection handling method (I've checked that, I have deleted closures and it still isn't called).

Additional info:

Request is created like here:

let url = URL(string: https://...)
var request = URLRequest(url: url)

request.addValue([someValue], forHTTPHeaderField: "User-Agent")

And this is my task:

let task = session.dataTask(with: request) // Request created like above
task.resume()

And will Combine methods (.dataTaskPubliser()) apply to that delegate?

Oschły
  • 53
  • 1
  • 7

1 Answers1

0

I found that's probably a bug (reported). Combine's publisher of URLSessionDataTask just doesn't call some methods of the delegate. Switched for now to classic Foundation's implementation.

Oschły
  • 53
  • 1
  • 7