From bf3562d51189bd4ef8c8b167229a8e493f78064b Mon Sep 17 00:00:00 2001 From: David Beck Date: Thu, 22 Mar 2018 16:57:09 -0700 Subject: [PATCH] Fix redirect handling According to the docs for URLSessionTaskDelegate, redirects should return the original response body, not an error if the redirect was rejected. https://developer.apple.com/documentation/foundation/urlsessiontaskdelegate/1411626-urlsession# --- Hippolyte/HTTPStubURLProtocol.swift | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/Hippolyte/HTTPStubURLProtocol.swift b/Hippolyte/HTTPStubURLProtocol.swift index 3ea0fc8..5423061 100644 --- a/Hippolyte/HTTPStubURLProtocol.swift +++ b/Hippolyte/HTTPStubURLProtocol.swift @@ -44,22 +44,20 @@ final class HTTPStubURLProtocol: URLProtocol { let response = HTTPURLResponse(url: url, statusCode: statusCode, httpVersion: nil, headerFields: stubbedResponse.headers) - if statusCode < 300 || statusCode > 399 || statusCode == 304 || statusCode == 305 { - let body = stubbedResponse.body - client?.urlProtocol(self, didReceive: response!, cacheStoragePolicy: .notAllowed) - client?.urlProtocol(self, didLoad: body!) - client?.urlProtocolDidFinishLoading(self) - } else { + if 300...399 ~= statusCode && (statusCode != 304 || statusCode != 305) { guard let location = stubbedResponse.headers["Location"], let url = URL(string: location), let cookies = cookieStorage.cookies(for: url) else { return } var redirect = URLRequest(url: url) redirect.allHTTPHeaderFields = HTTPCookie.requestHeaderFields(with: cookies) - - client?.urlProtocol(self, wasRedirectedTo: redirect, redirectResponse: response!) - let error = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil) - client?.urlProtocol(self, didFailWithError: error) + + client?.urlProtocol(self, wasRedirectedTo: redirect, redirectResponse: response!) } + + let body = stubbedResponse.body + client?.urlProtocol(self, didReceive: response!, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: body!) + client?.urlProtocolDidFinishLoading(self) } }