Swift - How to subclass NSMutableURLRequest correctly?

449 Views Asked by At

I have subclasses NSMutableURLRequest as follows:

class CustomNSMutableURLRequest: NSMutableURLRequest {

    convenience init(url : URL) {
        self.init(url: url)
        self.httpShouldHandleCookies = false
        self.httpMethod = "GET"
        print("Custom Request!")

    }
}

This causes an infinite loop at the self.init(url: url) line. Using super instead of self doesn't work either. How can I fix this?

2

There are 2 best solutions below

1
OOPer On BEST ANSWER

Unfortunately, you cannot override the exact convenience initializer within a subclass.

You may need to write something like this:

class CustomNSMutableURLRequest: NSMutableURLRequest {

    convenience init(url : URL) {
        self.init(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60)
        self.httpShouldHandleCookies = false
        self.httpMethod = "GET"
        print("Custom Request!")
    }
}

But I'm not sure if subclassing is really needed, I would add some factory method to URLRequest like this:

extension URLRequest {

    public static func customRequest(url: URL) -> URLRequest {
        var result = URLRequest(url: url)
        result.httpShouldHandleCookies = false
        result.httpMethod = "GET"
        print("Custom Request!")
        return result
    }
}
1
dgatwood On

In my experience, you cannot safely subclass NSURLRequest. If you do, you will get fascinating misbehavior with NSURLSession in which responses for one request get incorrectly associated with different requests.

Find a different way, such as using the methods designed for NSURLProtocol to attach arbitrary strings to the request, and attach a string containing a UUID, then use that as a dictionary key. Or use the session identifier in conjunction with the per-task identifier. Either way.