Swift - How to subclass NSMutableURLRequest correctly?

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?

Upvotes: 0

Views: 467

Answers (2)

dgatwood
dgatwood

Reputation: 10417

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.

Upvotes: 3

OOPer
OOPer

Reputation: 47896

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
    }
}

Upvotes: 2

Related Questions