我可以创建一个NSURL引用内存中的NSData? [英] Can I create an NSURL that refers to in-memory NSData?
问题描述
的文档NSURL
说明:
NSURL对象表示一个可能包含
远程服务器上资源的位置,
磁盘上的本地文件的路径,或者甚至 任意编码数据。 >
An NSURL object represents a URL that can potentially contain the location of a resource on a remote server, the path of a local file on disk, or even an arbitrary piece of encoded data.
我有一个内存中的数据块,我想要一个库,想通过<$ c加载资源$ c> NSURL 。当然,我可以先把这个 NSData
写入一个临时文件,然后创建一个文件://
NSURL
,但我更喜欢让URL直接指向我已经在内存中存在的缓冲区。
I have a blob of in-memory data that I'd like to hand to a library that wants to load a resource via an NSURL
. Sure, I can first write this NSData
to a temp file and then create a file://
NSURL
from that, but I'd prefer to have the URL point directly to the buffer that I already have present in memory.
上面引用的文档似乎暗示这是可能的,但我找不到任何提示如何完成它。
The docs quoted above seem to suggest this is possible, but I can't find any hint of how to accomplish it. Am I missing something?
推荐答案
NSURL
支持数据://网址计划( RFC 2397 )。
此计划允许您以
NSURL
supports the data:// URL-Scheme (RFC 2397).
This scheme allows you to build URLs in the form of
data://data:MIME-Type;base64,<data>
一个可行的Cocoa例子是:
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];
由于base64编码的性质,使用数据URL传递大型二进制blob可能有点低效。
Passing around large binary blobs with data URLs might be a bit inefficient due to the nature of base64 encoding.
您还可以实施自定义 NSURLProtocol ,专门处理您的数据。
Apple有一些示例代码,使用自定义协议传递图像对象:https://developer.apple.com/library/mac/samplecode/SpecialPictureProtocol/Introduction/Intro.html#//apple_ref/doc/uid/DTS10003816
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
这篇关于我可以创建一个NSURL引用内存中的NSData?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!