Can I create an NSURL that refers to in-memory NSData?

后端 未结 2 1219
借酒劲吻你
借酒劲吻你 2021-02-01 15:46

The docs for NSURL state that:

An NSURL object represents a URL that can potentially contain the location of a resource on a remote server, the path of

2条回答
  •  难免孤独
    2021-02-01 16:05

    NSURL supports the data:// URL-Scheme (RFC 2397).
    This scheme allows you to build URLs in the form of

    data://data:MIME-Type;base64,
    

    A working Cocoa example would be:

    NSImage* img = [NSImage imageNamed:@"img"];
    NSData* imgData = [img TIFFRepresentation];
    NSString* dataFormatString = @"data:image/png;base64,%@";
    NSString* dataString = [NSString stringWithFormat:dataFormatString, [imgData base64EncodedStringWithOptions:0]];
    NSURL* dataURL = [NSURL URLWithString:dataString];
    

    Passing around large binary blobs with data URLs might be a bit inefficient due to the nature of base64 encoding.

    You could also implement a custom NSURLProtocol that specifically deals with your data. Apple has some sample code that uses a custom protocol to pass around image objects: https://developer.apple.com/library/mac/samplecode/SpecialPictureProtocol/Introduction/Intro.html#//apple_ref/doc/uid/DTS10003816

提交回复
热议问题