且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自定义 URL 方案作为现有 URL 方案的适配器

更新时间:2023-11-26 22:58:22

Cocoa 中没有内置适配器,但是对于大多数用途,使用 NSURLProtocol 编写自己的适配器非常简单.给定一个任意 URL,像这样编码似乎最简单:

There's no built-in adaptor in Cocoa, but writing your own using NSURLProtocol is pretty straightforward for most uses. Given an arbitrary URL, encoding it like so seems simplest:

myscheme:<originalurl>

例如:

myscheme:http://example.com/path

最简单的说,NSURL 实际上只关心你传入的字符串是否是一个有效的 URI,如上所示.是的,基于 RFC 1808 等,有额外的 URL 支持位于顶部,但这不是必需的.

At its simplest, NSURL only actually cares if the string you pass in is a valid URI, which the above is. Yes, there is then extra URL support layered on top, based around RFC 1808 etc. but that's not essential.

成为有效 URI 所需要的只是一个指示方案的冒号,并且没有无效字符(基本上是没有空格的 ASCII).

All that's required to be a valid URI is a colon to indicate the scheme, and no invalid characters (basically, ASCII without spaces).

然后您可以使用 -resourceSpecifier 方法来检索原始 URL 并使用它.

You can then use the -resourceSpecifier method to retrieve the original URL and work with that.