Skip to content

Commit

Permalink
Fix loss of session delegate & session invalidation control.
Browse files Browse the repository at this point in the history
SwiftLinkPreview's public API is one that asks the user for a
URLSession. This API gives the user the freedom to fully configure their
own URLSession (such as by setting a custom delegate) as well as giving
them control over invalidating the session through
finishTasksAndInvalidate() or invalidateAndCancel().

Internally, however, at some point SwiftLinkPreview re-creates the
URLSession in order to set its own delegate. This is bad form because it
belies the public API, resulting in behaviour that violates its own
contract: now the URLSession that was given to it no longer honours the
user's URLSessionDelegate and it ignores invalidation calls.

Either SwiftLinkPreview should have a public API that *only* asks for a
URLSessionConfiguration and then make its own URLSessions off that, or
it should ask for a URLSession and then honour that contract without
internally changing the actual session used.

This solution does the latter.

Note that SwiftLinkPreview's replacement delegate appears to be purely
to ensure redirects are happening, but this is already the automatic
behaviour for background-style URLSessions (which are probably the type
you want to use with SwiftLinkPreview anyway). If the user wants
redirects without a background-style URLSession, he should handle that
in his own URLSession. Note that the behaviour of URLSession is
100% out-of-scope for SwiftLinkPreview, especially when SwiftLinkPreview
is asking the user for what session to use.
  • Loading branch information
lhunath committed Jun 7, 2022
1 parent 5cbefb7 commit f84740e
Showing 1 changed file with 0 additions and 18 deletions.
18 changes: 0 additions & 18 deletions Sources/SwiftLinkPreview.swift
Expand Up @@ -86,10 +86,6 @@ open class SwiftLinkPreview: NSObject {

let cancellable = Cancellable()

self.session = URLSession(configuration: self.session.configuration,
delegate: self, // To handle redirects
delegateQueue: self.session.delegateQueue)

let successResponseQueue = { (response: Response) in
if !cancellable.isCancelled {
self.responseQueue.async {
Expand Down Expand Up @@ -827,17 +823,3 @@ extension SwiftLinkPreview {
}

}

extension SwiftLinkPreview: URLSessionDataDelegate {

public func urlSession(_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void) {
var request = request
request.httpMethod = "GET"
completionHandler(request)
}

}

0 comments on commit f84740e

Please sign in to comment.