Make an NSURL with an encoded plus (+)

前端 未结 7 1158
北海茫月
北海茫月 2021-02-14 01:32

I need to pass a timestamp with a timezone offset in a GET request, e.g.,

2009-05-04T11:22:00+01:00

This looks like a two arguments

相关标签:
7条回答
  • 2021-02-14 02:05

    To get encoded plus (%2B) (It works with all charcters) use CFURLCreateStringByAddingPercentEscapes as

    /**
     get parameterized url from url and query parameters.
     */
    +(NSString *)getParameterizedUrl:(NSString *)url withParameters:(NSDictionary *)queryDictionary
    {
        NSMutableArray *mutablePairs = [NSMutableArray array];
        for (NSString *key in queryDictionary) {
            [mutablePairs addObject:[NSString stringWithFormat:@"%@=%@", CTPercentEscapedQueryStringKeyFromStringWithEncoding(key, NSUTF8StringEncoding), CTPercentEscapedQueryStringValueFromStringWithEncoding(queryDictionary[key], NSUTF8StringEncoding)]];
        }
    
        return [[NSString alloc]initWithFormat:@"%@?%@",url,[mutablePairs componentsJoinedByString:@"&"]];
    }
    
    static NSString * const kCharactersToBeEscapedInQueryString = @":/?&=;+!@#$()',*";
    
    static NSString * CTPercentEscapedQueryStringKeyFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
        static NSString * const kCharactersToLeaveUnescapedInQueryStringPairKey = @"[].";
    
        return (__bridge_transfer  NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, (__bridge CFStringRef)kCharactersToLeaveUnescapedInQueryStringPairKey, (__bridge CFStringRef)kCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding));
    }
    
    static NSString * CTPercentEscapedQueryStringValueFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
        return (__bridge_transfer  NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)kCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding));
    }
    

    And use in your code as

    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:@"2009-05-04T11:22:00+01:00" forKey:@"timestamp"];
    
    NSString *urlString = [self getParameterizedUrl:@"http://www.example.com" withParameters:params];
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    0 讨论(0)
提交回复
热议问题