How do I URL encode a string

2018-12-31 09:01发布

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

21条回答
查无此人
2楼-- · 2018-12-31 09:37

swift code based on chown's objc answer in this thread.

extension String {
    func urlEncode() -> String {
        return CFURLCreateStringByAddingPercentEscapes(
            nil,
            self,
            nil,
            "!*'();:@&=+$,/?%#[]",
            CFStringBuiltInEncodings.UTF8.rawValue
        )
    }
}
查看更多
孤独寂梦人
3楼-- · 2018-12-31 09:37

In swift 3:

// exclude alpha and numeric == "full" encoding
stringUrl = stringUrl.addingPercentEncoding(withAllowedCharacters: .alphanumerics)!;

// exclude hostname and symbols &,/ and etc
stringUrl = stringUrl.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!;
查看更多
与君花间醉酒
4楼-- · 2018-12-31 09:37

For individual www form-encoded query parameters, I made a category on NSString:

- (NSString*)WWWFormEncoded{
     NSMutableCharacterSet *chars = NSCharacterSet.alphanumericCharacterSet.mutableCopy;
     [chars addCharactersInString:@" "];
     NSString* encodedString = [self stringByAddingPercentEncodingWithAllowedCharacters:chars];
     encodedString = [encodedString stringByReplacingOccurrencesOfString:@" " withString:@"+"];
     return encodedString;
}
查看更多
登录 后发表回答