iOS : How to do proper URL encoding?

后端 未结 10 1881
一整个雨季
一整个雨季 2020-12-13 19:20

I\'m unable to open a URL into UIWebView so I\'ve seached & found that I need to encode URL, so I tried to encode it but, I\'ve facing problem in URL encodi

相关标签:
10条回答
  • 2020-12-13 19:39

    You can try this

    NSString *url = @"http://www.abc.com/param=Hi how are you";
    
    NSString* encodedUrl = [url stringByAddingPercentEscapesUsingEncoding:
     NSASCIIStringEncoding];
    
    0 讨论(0)
  • 2020-12-13 19:43

    This may useful to someone who's reach to this question for URL encoding, as my question likely different which has been solved and accepted, this is the way I used to do encoding,

    -(NSString *)encodeURL:(NSString *)urlString
    {
        CFStringRef newString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlString, NULL, CFSTR("!*'();:@&=+@,/?#[]"), kCFStringEncodingUTF8);
        return (NSString *)CFBridgingRelease(newString);
    }
    
    0 讨论(0)
  • 2020-12-13 19:47

    The most straightforward way is to use:

    NSString *encodedString = [rawString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    

    iDhaval was close, but he was doing it the other way around (decoding instead of encoding).

    Anand's way would work, but you'll most likely have to replace more characters than spaces and new lines. See the reference here: http://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters

    Hope that helps.

    0 讨论(0)
  • 2020-12-13 19:48

    I think this will work for you

    [strUrl stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]
    

    the Native method for URL Encoding.

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