Search code examples
swiftsubclassnsurlsessionnsmutableurlrequest

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?


Solution

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