Skip to content

URLSessionInstrumentation doesn't call the urlSession(_:dataTask:didReceive:) method #759

@ddas09

Description

@ddas09

Description:
I am encountering an issue where the URLSessionInstrumentation fails to swizzle the urlSession(_:dataTask:didReceive:) method in a custom delegate class. While the instrumentation works for other delegate methods like urlSession(_:task:didFinishCollecting:), it does not intercept the urlSession(_:dataTask:didReceive:) method.

Here is my code -

public class CustomSessionDelegate: NSObject, URLSessionDataDelegate, URLSessionTaskDelegate {
    public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        print("Data received")
    }
}

let delegate = CustomSessionDelegate()
let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)

let networkInstrumentation = URLSessionInstrumentation(
    configuration: URLSessionInstrumentationConfiguration(
        delegateClassesToInstrument: [CustomSessionDelegate.self]
    )
)

Expected Behavior:
The injectTaskDidReceiveDataIntoDelegateClass method should find the urlSession(_:dataTask:didReceive:) method in the delegate class and swizzle it for instrumentation.

More Info
When debugging, I saw the code never goes into this and skips this block (not sure though why) -

let block:
      @convention(block) (Any, URLSession, URLSessionTask, URLSessionTaskMetrics) -> Void = { object, session, task, metrics in
        if objc_getAssociatedObject(session, &idKey) == nil {
          self.urlSession(session, task: task, didFinishCollecting: metrics)
        }
        let key = String(selector.hashValue)
        objc_setAssociatedObject(session, key, true, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        let castedIMP = unsafeBitCast(originalIMP,
                                      to: (@convention(c) (Any, Selector, URLSession, URLSessionTask, URLSessionTaskMetrics) -> Void).self)
        castedIMP(object, selector, session, task, metrics)
        objc_setAssociatedObject(session, key, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
      }

Note: urlSession(_:task:didFinishCollecting:) - this method seems to work fine though with the same instrumentation.

It's been a blocker for us!

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingquestionFurther information is requested

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions