Search code examples
iphoneobjective-ciosnsurl

NSURL with Curly Braces


NSURL does not support the use of curly braces (i.e. {}) in URLs. My application needs to talk to a server that requires the use of curly braces in the URL. I'm considering using bridges to write the networking code in Python or C++, or even rewriting the C code for NSURL to make it accept curly braces. Percent escapes are not accepted by my remote server.

Do I have any other good alternatives?

EDIT: Explained why addingPercentEscapesUsingEncoding and the like don't work for me here.


Solution

  • Will it work for you if you escape the braces?

    This code:

    // escape {} with %7B and %7D
    NSURL *url = [NSURL URLWithString:@"http://somesite.com/%7B7B643FB915-845C-4A76-A071-677D62157FE07D%7D.htm"];
    NSLog(@"%@", url);
    
    // {} don't work and return null
    NSURL *badurl = [NSURL URLWithString:@"http://somesite.com/{7B643FB915-845C-4A76-A071-677D62157FE07D}.htm"];
    NSLog(@"%@", badurl);
    

    Outputs:

    2011-11-30 21:25:06.655 Craplet[48922:707] http://somesite.com/%7B7B643FB915-845C-4A76-A071-677D62157FE07D%7D.htm
    2011-11-30 21:25:06.665 Craplet[48922:707] (null)
    

    So, escaping seems to work

    Here's how you can programmatically escape the url:

    NSString *escapedUrlString = [unescaped stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding];
    

    EDIT:

    In your comment below, you said your server won't accept encoded braces and was there any other alternatives. First, I would try and get the server fixed. If that's not possible ... I haven't tried this with braces etc... but the layer below NS networking classes is CFNetworking.

    See this:

    http://developer.apple.com/library/ios/#documentation/Networking/Conceptual/CFNetwork/CFHTTPTasks/CFHTTPTasks.html#//apple_ref/doc/uid/TP30001132-CH5-SW2

    From that doc:

     CFStringRef url = CFSTR("http://www.apple.com");
     CFURLRef myURL = CFURLCreateWithString(kCFAllocatorDefault, url, NULL);
     CFStringRef requestMethod = CFSTR("GET");
    
     ....
    

    Once again, haven't tried it and I'm running out. might try it later but if a layer isn't working your first options are to move down the stack.