Replacement for stringByAddingPercentEscapesUsingEncoding in ios9?

后端 未结 8 1565
耶瑟儿~
耶瑟儿~ 2020-11-29 01:09

In iOS8 and prior I can use:

NSString *str = ...; // some URL
NSString *result = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
         


        
8条回答
  •  执笔经年
    2020-11-29 01:19

    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;
    }
    }
    

提交回复
热议问题