IT

ios9에서 stringByAddingPercentEscapesUsingEncoding을 대체할까요?

lottoking 2020. 8. 9. 09:13
반응형

ios9에서 stringByAddingPercentEscapesUsingEncoding을 대체할까요?


iOS8 및 이전 버전에서는 다음을 사용할 수 있습니다.

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

iOS9에서 다음으로 stringByAddingPercentEscapesUsingEncoding대체 stringByAddingPercentEncodingWithAllowedCharacters.

NSString *str = ...; // some URL
NSCharacterSet *set = ???; // where to find set for NSUTF8StringEncoding?
NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:set];

내 질문은 : 적절한 교체 를 위해 필요한 NSCharacterSet( NSUTF8StringEncoding)을 어디에서 stringByAddingPercentEscapesUsingEncoding있습니까?


지원 중단 메시지는 다음과 가변합니다.

대신 항상 권장되는 UTF-8 인코딩 을 사용하고 각 URL 구성 요소 또는 하위 구성 요소에 유효한 문자에 대한 규칙이 다르기 때문에 특정 URL 구성 요소 또는 하위 구성 요소를 인코딩하는 stringByAddingPercentEncodingWithAllowedCharacters (_ :)를 대신 사용하십시오 .

따라서 인수 NSCharacterSet적절한 만 제공하면 됩니다. 다양한 URL의 경우 URLHostAllowedCharacterSet다음과 같이 사용할 수 있는 매우 편리한 클래스 방법이 있습니다.

let encodedHost = unencodedHost.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())

스위프트 3 업데이트 - 메서드가 정적 속성이됩니다 urlHostAllowed.

let encodedHost = unencodedHost.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

그러나 다음 사항에 유의하십시오.

이 메소드는 전체 URL이 아닌 URL 구성 요소 또는 하위 구성 요소를 퍼센트 인코딩하기위한 것입니다.


Objective-C의 경우 :

NSString *str = ...; // some URL
NSCharacterSet *set = [NSCharacterSet URLHostAllowedCharacterSet]; 
NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:set];

NSUTF8StringEncoding에 대한 집합은 어디에서 있습니까?

인코딩 인코딩을 허용하는 6 개의 URL 구성 요소 및 하위 구성 요소에 대해 미리 정의 된 문자 집합이 있습니다. 이제는 문자 집합이 전달 -stringByAddingPercentEncodingWithAllowedCharacters:됩니다.

 // Predefined character sets for the six URL components and subcomponents which allow percent encoding. These character sets are passed to -stringByAddingPercentEncodingWithAllowedCharacters:.
@interface NSCharacterSet (NSURLUtilities)
+ (NSCharacterSet *)URLUserAllowedCharacterSet;
+ (NSCharacterSet *)URLPasswordAllowedCharacterSet;
+ (NSCharacterSet *)URLHostAllowedCharacterSet;
+ (NSCharacterSet *)URLPathAllowedCharacterSet;
+ (NSCharacterSet *)URLQueryAllowedCharacterSet;
+ (NSCharacterSet *)URLFragmentAllowedCharacterSet;
@end

지원 중단 메시지는 다음과 가변합니다.

대신 항상 권장되는 UTF-8 인코딩 을 사용하고 각 URL 구성 요소 또는 하위 구성 요소에 유효한 문자에 대한 규칙이 다르기 때문에 특정 URL 구성 요소 또는 하위 구성 요소를 인코딩하는 stringByAddingPercentEncodingWithAllowedCharacters (_ :)를 대신 사용하십시오 .

따라서 인수 NSCharacterSet적절한 만 제공하면 됩니다. 다양한 URL의 경우 URLHostAllowedCharacterSet다음과 같이 사용할 수 있는 매우 편리한 클래스 방법이 있습니다.

NSCharacterSet *set = [NSCharacterSet URLHostAllowedCharacterSet]; 

그러나 다음 사항에 유의하십시오.

이 메소드는 전체 URL이 아닌 URL 구성 요소 또는 하위 구성 요소를 퍼센트 인코딩하기위한 것입니다.


URLHostAllowedCharacterSet되어 작동하지 ME하십시오. URLFragmentAllowedCharacterSet대신 사용 합니다.

목표 -C

NSCharacterSet *set = [NSCharacterSet URLFragmentAllowedCharacterSet];
NSString * encodedString = [@"url string" stringByAddingPercentEncodingWithAllowedCharacters:set];

SWIFT-4

"url string".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

다음은 유용한 (반전 된) 문자 세트입니다.

URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}
URLHostAllowedCharacterSet      "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet     "#%<>[\]^`{|}
URLUserAllowedCharacterSet      "#%/:<>?@[\]^`

목표 -C

이 코드는 나를 위해 작동합니다.

urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];

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

Swift 3.0의 경우

urlHostAllowedcharacterSet 을 (를) 사용할 수 있습니다 .

/// 호스트 URL 하위 구성 요소에서 허용되는 문자에 대한 문자 집합을 반환합니다.

public static var urlHostAllowed: CharacterSet { get }

WebserviceCalls.getParamValueStringForURLFromDictionary(settingsDict as! Dictionary<String, AnyObject>).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)

"이 메소드는 전체 URL URL이 아닌 URL 구성 요소 또는 하위 구성 요소입니다."의 의미는 무엇입니까? ? – GeneCode '16 년 9 월 1 일 8시 30 분

이는 https://xpto.example.com/path/subpathURL 의을 인코딩해서는 안되지만 ?.

다음과 같은 경우에 사용 사례가 있기 때문에 가정합니다.

https://example.com?redirectme=xxxxx

xxxxx완전히 인코딩 된 URL은 어디에 있습니까 ?


수락 된 답변에 추가. 이 메모를 고려

이 메서드는 전체 URL 문자열이 아닌 URL 구성 요소 또는 하위 구성 요소 문자열을 퍼센트 인코딩하기위한 것입니다.

전체 URL을 인코딩해서는 안됩니다.

let param = "=color:green|\(latitude),\(longitude)&\("zoom=13&size=\(width)x\(height)")&sensor=true&key=\(staticMapKey)".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) 
let url = "https://maps.google.com/maps/api/staticmap?markers" + param!

참고 URL : https://stackoverflow.com/questions/32242712/replacement-for-stringbyaddingpercentescapesusingencoding-in-ios9

반응형