Encoding string arguments for URLs

后端 未结 3 690
误落风尘
误落风尘 2021-01-25 03:22

I created a method to build URLs for me.

- (NSString *)urlFor:(NSString *)path arguments:(NSDictionary *)args
{
    NSString *format = @\"http://api.example.com/         


        
相关标签:
3条回答
  • 2021-01-25 03:42

    IIRC, slashes should be interpreted properly when they're in the query part of a URL. Did you test to see if it still works without encoded slashses? Otherwise, do something like:

    if ([args isKindOfClass:[NSDictionary class]]) {
            for (NSString *key in [args allKeys]) {
                NSString *value = [(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)[args objectForKey:key], NULL, CFSTR("/?&:=#"), kCFStringEncodingUTF8) autorelease];
                [url appendString:[NSString stringWithFormat:@"&%@=%@", key, value]];
                [value release];
            }
    }
    
    return url;
    

    Note the value of the 4th argument to CFURLCreateStringByAddingPercentEscapes.

    0 讨论(0)
  • 2021-01-25 03:42

    I'd recommend our KSFileUtilities set of classes. Your example would then be:

    - (NSString *)urlFor:(NSString *)path arguments:(NSDictionary *)args
    {
        NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:args];
        [parameters setObject:@"2.0.1" forKey:@"version"];
    
        NSURL *result = [NSURL ks_URLWithScheme:@"http"
                                           host:@"api.example.com"
                                           path:path
                                queryParameters:parameters;
    
        return [result absoluteString];
    }
    
    0 讨论(0)
  • 2021-01-25 03:44

    You should consider using Google Toolbox for Mac's GTMNSString+URLArguments; it's designed for exactly this purpose.

    0 讨论(0)
提交回复
热议问题