How do I URL encode a string

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

    In my case where the last component was Arabic letters I did the following in Swift 2.2:

    extension String {
    
     func encodeUTF8() -> String? {
    
        //If I can create an NSURL out of the string nothing is wrong with it
        if let _ = NSURL(string: self) {
    
            return self
        }
    
        //Get the last component from the string this will return subSequence
        let optionalLastComponent = self.characters.split { $0 == "/" }.last
    
    
        if let lastComponent = optionalLastComponent {
    
            //Get the string from the sub sequence by mapping the characters to [String] then reduce the array to String
            let lastComponentAsString = lastComponent.map { String($0) }.reduce("", combine: +)
    
    
            //Get the range of the last component
            if let rangeOfLastComponent = self.rangeOfString(lastComponentAsString) {
                //Get the string without its last component
                let stringWithoutLastComponent = self.substringToIndex(rangeOfLastComponent.startIndex)
    
    
                //Encode the last component
                if let lastComponentEncoded = lastComponentAsString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet()) {
    
    
                //Finally append the original string (without its last component) to the encoded part (encoded last component)
                let encodedString = stringWithoutLastComponent + lastComponentEncoded
    
                    //Return the string (original string/encoded string)
                    return encodedString
                }
            }
        }
    
        return nil;
    }
    }
    

    usage:

    let stringURL = "http://xxx.dev.com/endpoint/nonLatinCharacters"
    
    if let encodedStringURL = stringURL.encodeUTF8() {
    
        if let url = NSURL(string: encodedStringURL) {
    
          ...
        }
    
    } 
    

提交回复
热议问题