抓取CocoaURL编码的22

Catch 22 of Cocoa URL encoding

在检查了其他人如何尝试在 Cocoa 中进行 URL 编码(如 How do I URL encode a string, Swift - encode URL 等)之后,我仍然不知道如何正确地 URL 编码Cocoa 如果

第 22 条:

如何在这种情况下 URL 正确编码而不编写我自己的 URL 解析器、编码器?

您应该阅读本主题的所有 Apple's release note discussion,但特别是这部分可能与您的案例最相关:

If you need to percent-encode an entire URL string, you can use this code to encode a NSString intended to be a URL (in urlStringToEncode):

    NSString *percentEncodedURLString =
       [[NSURL URLWithDataRepresentation:[urlStringToEncode dataUsingEncoding:NSUTF8StringEncoding] relativeToURL:nil] relativeString];

(The CoreFoundation equivalent to URLWithDataRepresentation: is CFURLCreateWithBytes() using the encoding kCFStringEncodingUTF8 with a fall back to kCFStringEncodingISOLatin1 if kCFStringEncodingUTF8 fails.)

基本上,+URLWithDataRepresentation:relativeToURL: 会尽最大努力从提供的字节中生成正确的 URL。鉴于您几乎无法保证输入的任何内容,因此无法保证它会得到它 "right" (因为 "right" 在这种情况下没有明确定义),但它可能是你最大的希望。