How do I URL encode a string

前端 未结 22 1711
轮回少年
轮回少年 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:03

    In Swift 3, please try out below:

    let stringURL = "YOUR URL TO BE ENCODE";
    let encodedURLString = stringURL.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
    print(encodedURLString)
    

    Since, stringByAddingPercentEscapesUsingEncoding encodes non URL characters but leaves the reserved characters (like !*'();:@&=+$,/?%#[]), You can encode the url like the following code:

    let stringURL = "YOUR URL TO BE ENCODE";
    let characterSetTobeAllowed = (CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted)
    if let encodedURLString = stringURL.addingPercentEncoding(withAllowedCharacters: characterSetTobeAllowed) {
        print(encodedURLString)
    }
    

提交回复
热议问题