Question

I have the following code to start my own Cocoa HTTP Server. In order to manually handle the responses I have created my custom HTTPConnection class named PictureHTTPConnection

self.httpServer = [[HTTPServer alloc]init];
self.httpServer.type = @"_http._tcp.";
self.httpServer.name = @"MyBonjour Name";
self.httpServer.connectionClass = [PictureHTTPConnection class];

The problem here is that the PictureHTTPConnection class needs some information in order to handle the HTTP connections. However, I only provide the class and therefore I don't have a reference to the instance. I could do something with global data but this is not very good programming practise.

The best way I can think of is setting the PictureHTTPConnection's delegate to the UIApplicationDelegate so that it can answer any callbacks. :-(

Was it helpful?

Solution

I had the same exact problem. To solve this, I changed the code of the HTTPServer class so that you can set it a delegate that will in turn be set on each HTTPConnection created. When the HTTPConnection has to handle the request I call the delegate. This is far from clean as well and I was seeking for a better solution.

OTHER TIPS

You can get callbacks by adding a category to HTTPServer that gets & sets a delegate. objc_setAssociatedObject is your friend here:

@interface HTTPServer (WithDelegate)
    @property (strong, nonatomic) id delegate;
@end

@implementation HTTPServer (WithDelegate)
    NSString const *key = @"HttpServer.WithDelegate.key";
    - (void)setDelegate:(id)delegate
    {
        objc_setAssociatedObject(self, &key, delegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    - (id)delegate
    {
        return objc_getAssociatedObject(self, &key);
    }
@end

Set the delegate when you initialize the HTTPServer instance (or whenever). Call methods on it from your custom HTTPConnection implementation like this:

[config.server.delegate handleRequest:theRequest];

You must implement handleRequest:(Whatever*)theRequest in your delegate class

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top