How do I URL encode a string

前端 未结 22 1704
轮回少年
轮回少年 2020-11-22 07:16

I have a URL string (NSString) with spaces and & characters. How do I url encode the entire string (including the & ampersand

22条回答
  •  醉酒成梦
    2020-11-22 08:14

    This might be helpful

    NSString *sampleUrl = @"http://www.google.com/search.jsp?params=Java Developer";
    NSString* encodedUrl = [sampleUrl stringByAddingPercentEscapesUsingEncoding:
     NSUTF8StringEncoding];
    

    For iOS 7+, the recommended way is:

    NSString* encodedUrl = [sampleUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    

    You can choose the allowed character set as per the requirement of the URL component.

提交回复
热议问题