Search code examples
ioshyperlinkdownloadnsdatacocoahttpserver

CocoaHTTPServer on iOS: set up server so user can download NSData as file


I want to make the following webpage using CocoaHTTPServer: there should be a link to download a file, but the source file must be NSData object in memory.

As far as I see in samples, there is an easy way to link some file on iPhone to the hyperlink. Is it possible to "link" NSData?

Would be very thankful for examples.


Solution

  • All you need to do is to return HTTPDataResponse in your HTTPConnection subclass.

    If you want an example have a look at the CocoaHTTPServer sample called DynamicServer and replace - httpResponseForMethod: URI: in MyHTTPConnection with something similar to the following:

    - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
    {
        // Before returning you can analyze the passed path argument and select the correct data object to return...
        return [[HTTPDataResponse alloc] initWithData:placeYourDataInstanceHere];
    }