Comparison between NSMutableURLRequest and URLRequest in URLProtocol implememtation

352 Views Asked by At

The NSURLProtocol documentation says it is possible to set a key-value and associate it with a request. The documentation calls it "tagging a request".

class func property(forKey: String, in: URLRequest)

Returns the property associated with the specified key in the specified request.

class func setProperty(Any, forKey: String, in: NSMutableURLRequest)

Sets the property associated with the specified key in the specified request.

My objective is to: from the outside of my MYURLProtocol, associate a value with a request, through a class/static method - and subsequently get it out again using a request.

This works:

class func methodOnURLProtocolConcreteClass(value: Any, request: URLRequest) {
    let mutableRequest = request as! NSMutableURLRequest
    URLProtocol.setProperty(value, forKey: "value", in: mutableRequest)
    let loadedValue = URLProtocol.property(forKey: "value", in: mutableRequest as URLRequest)
    print(loadedValue) // Success!, prints out value
}

// call site
MyURLProtocol.methodOnURLProtocolConcreteClass(value: "Hello", request: request)

So some casting is needed because the signatures of the getter and setter of the property uses NSMutableURLRequest to set the value and URLRequest to get it out again.

If I do the same thing, but spread out over 2 methods:

class func methodOnURLProtocolConcreteClass(value: Any, request: URLRequest) {
    let mutableRequest = request as! NSMutableURLRequest
    URLProtocol.setProperty(value, forKey: "value", in: mutableRequest)
}

class func anotherMethodOnURLProtocolConcreteClass(request: URLRequest) {
    let loadedValue = URLProtocol.property(forKey: "value", in: request)
    print(loadedValue) // Failure!, loadedValue is nil
}

// call site
MyURLProtocol.methodOnURLProtocolConcreteClass(value: "Hello", request: request)
MyURLProtocol.anotherMethodOnURLProtocolConcreteClass(request: request)

So my suspicion is that somewhere along the cast/conversion back and forth from Swift URLRequest to Obj-C NSMutableURLRequest this object is "shallow copied" or similar to create the Swift value type and that causes it to loose association with the properties store on it.

Thanks

0

There are 0 best solutions below