Last active
June 10, 2020 11:16
-
-
Save ncreated/c62b566368b1c05e1bbf117fe4ede68d to your computer and use it in GitHub Desktop.
Replacing URL with URLRequest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import PlaygroundSupport | |
let url = URL(string: "https://picsum.photos/200/300")! | |
private extension URLSession { | |
/// Method under test | |
func urlRequest(with url: URL) -> URLRequest { | |
return URLRequest( | |
url: url, | |
cachePolicy: configuration.requestCachePolicy, | |
timeoutInterval: configuration.timeoutIntervalForRequest | |
) | |
} | |
} | |
func testAgainst(configuration: URLSessionConfiguration) { | |
let session = URLSession(configuration: configuration) | |
var taskFromURLRef: URLSessionTask? | |
var taskFromRequestRef: URLSessionTask? | |
let taskFromURL = session.dataTask(with: url) { data, response, error in | |
print("Inspecting request for `.dataTask(with: url)`") | |
inspectCurrentRequestFor(task: taskFromURLRef!) | |
} | |
let request = session.urlRequest(with: url) | |
let taskFromRequest = session.dataTask(with: request) { data, response, error in | |
print("Inspecting request for `.dataTask(with: request)`") | |
inspectCurrentRequestFor(task: taskFromRequestRef!) | |
} | |
taskFromURLRef = taskFromURL | |
taskFromRequestRef = taskFromRequest | |
taskFromURL.resume() | |
taskFromRequest.resume() | |
sleep(4) // wait for requests completion | |
} | |
func inspectCurrentRequestFor(task: URLSessionTask) { | |
print(" → allHTTPHeaderFields:", task.currentRequest!.allHTTPHeaderFields!.sorted(by: <).map { k, v in "\(k): \(v)" }) | |
print(" → networkServiceType:", task.currentRequest!.networkServiceType.rawValue) | |
print(" → allowsCellularAccess:", task.currentRequest!.allowsCellularAccess) | |
print(" → timeoutInterval", task.currentRequest!.timeoutInterval) | |
print(" → httpShouldHandleCookies", task.currentRequest!.httpShouldHandleCookies) | |
} | |
testAgainst(configuration: { | |
let configuration = URLSessionConfiguration.ephemeral | |
configuration.httpAdditionalHeaders = ["foo": "bar"] | |
configuration.networkServiceType = .avStreaming | |
configuration.allowsCellularAccess = false | |
configuration.timeoutIntervalForRequest = 13 | |
configuration.timeoutIntervalForResource = 11 | |
configuration.httpCookieAcceptPolicy = .always | |
configuration.httpShouldSetCookies = true | |
return configuration | |
}()) | |
PlaygroundPage.current.needsIndefiniteExecution = true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: