programing

Objective-C 및 Swift URL 인코딩

closeapi 2023. 4. 11. 22:03
반응형

Objective-C 및 Swift URL 인코딩

나는 가지고 있다NSString다음과 같습니다.

http://www.

하지만 다음과 같이 변환하고 싶습니다.

http%3A%2F%2Fwww.

이거 어떻게 해?

원하는 캐릭터를 탈출하는 것은 조금 더 힘든 일이다.

코드 예시

iOS7 이상:

NSString *unescaped = @"http://www";
NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSLog(@"escapedString: %@", escapedString);

NSLog 출력:

excape String: http%3A%2F%2Fww

다음은 유용한 URL 인코딩 문자 세트입니다.

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

위의 모든 것을 조합한 문자 세트 작성:

NSCharacterSet *URLCombinedCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@" \"#%/:<>?@[\\]^`{|}"] invertedSet];

Base64 작성

Base64 문자 세트의 경우:

NSCharacterSet *URLBase64CharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@"/+=\n"] invertedSet];

Swift 3.0의 경우:

var escapedString = originalString.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)

Swift 2.x의 경우:

var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())

주의:stringByAddingPercentEncodingWithAllowedCharacters는 인코딩이 필요한 UTF-8 문자도 인코딩합니다.

iOS7 이전 버전에서는 Core Foundation 사용
ARC와 함께 코어 파운데이션 사용

NSString *escapedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
    NULL,
   (__bridge CFStringRef) unescaped,
    NULL,
    CFSTR("!*'();:@&=+$,/?%#[]\" "),
    kCFStringEncodingUTF8));

ARC를 사용하지 않는 코어 기초 사용:

NSString *escapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
    NULL,
   (CFStringRef)unescaped,
    NULL,
    CFSTR("!*'();:@&=+$,/?%#[]\" "),
    kCFStringEncodingUTF8);

주의:-stringByAddingPercentEscapesUsingEncoding는 올바른 인코딩을 생성하지 않습니다.이 경우 동일한 문자열을 반환하는 어떤 인코딩도 생성되지 않습니다.

stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding14 문자를 부호화합니다.

#%^{}[]|\"<>에 스페이스 문자(탈락율)를 추가합니다.

testString:

" `~!@#$%^&*()_+-={}[]|\\:;\"'<,>.?/AZaz"  

encoded String :

"%20%60~!@%23$%25%5E&*()_+-=%7B%7D%5B%5D%7C%5C:;%22'%3C,%3E.?/AZaz"  

주의: 필요에 따라 변경하지 않으면 이 문자 집합이 사용자의 요구를 충족하는지 고려하십시오.

인코딩이 필요한 RFC 3986 문자(인코딩 프리픽스 문자이므로 % 추가):

"!#$&'()*+/:;=?@[]%"

일부 "예약되지 않은 문자"는 추가로 인코딩됩니다.

"\n\r "%-"<>\^_'{|}~"

URL 인코딩이라고 합니다.여기 더 있어요.

-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
    return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
           (CFStringRef)self,
           NULL,
           (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
           CFStringConvertNSStringEncodingToEncoding(encoding));
}

이건 내 해결책이 아니야스택오버플로우에서 다른 사람이 썼는데 어떻게 썼는지 잊어버렸어요.

이 솔루션은 어떻게든 「잘」되고 있습니다.분음 문자, 한자, 기타 거의 모든 것을 처리합니다.

- (NSString *) URLEncodedString {
    NSMutableString * output = [NSMutableString string];
    const char * source = [self UTF8String];
    int sourceLen = strlen(source);
    for (int i = 0; i < sourceLen; ++i) {
        const unsigned char thisChar = (const unsigned char)source[i];
        if (false && thisChar == ' '){
            [output appendString:@"+"];
        } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
                   (thisChar >= 'a' && thisChar <= 'z') ||
                   (thisChar >= 'A' && thisChar <= 'Z') ||
                   (thisChar >= '0' && thisChar <= '9')) {
            [output appendFormat:@"%c", thisChar];
        } else {
            [output appendFormat:@"%%%02X", thisChar];
        }
    }
    return output;
}

누가 이 코드를 만들었는지 알려주시면 정말 감사하겠습니다.기본적으로 그는 왜 이 인코딩된 문자열이 원하는 대로 정확히 해독되는지 설명합니다.

나는 그의 해결책을 조금 수정했다.+보다 %20으로 표시되는 공간이 좋습니다.그게 다예요.

 NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NUL,(CFStringRef)@"parameter",NULL,(CFStringRef)@"!*'();@&+$,/?%#[]~=_-.:",kCFStringEncodingUTF8 );

NSURL * url = [[NSURL alloc] initWithString:[@"address here" stringByAppendingFormat:@"?cid=%@",encodedString, nil]];

이것은 목표 C ARC에서 작동할 수 있습니다.CFBridgingRelease를 사용하여 Core Foundation 스타일의 오브젝트를 Objective-C 오브젝트로 캐스팅하고 오브젝트의 소유권을 ARC로 이전합니다.여기서 Function CFBridging Release를 참조하십시오.

+ (NSString *)encodeUrlString:(NSString *)string {
return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes
                         (kCFAllocatorDefault,
                          (__bridge CFStringRef)string,
                          NULL,
                          CFSTR("!*'();:@&=+$,/?%#[]"),
                          kCFStringEncodingUTF8)
                         );}

신속한 iOS:

참고: 저는 이것을 사용했습니다.

extension String {

    func urlEncode() -> CFString {
        return CFURLCreateStringByAddingPercentEscapes(
            nil,
            self,
            nil,
            "!*'();:@&=+$,/?%#[]",
            CFStringBuiltInEncodings.UTF8.rawValue
        )
    }

}// end extension String

이게 내가 쓰는 거야.주의:@autoreleasepool기능 또는 프로그램이 충돌하거나 IDE가 잠길 수 있습니다.IDE를 3회 재기동하고 나서 수정을 깨달았습니다.이 코드는 ARC에 준거하고 있는 것 같습니다.

이 질문은 여러 번 제기되었고 많은 답변이 주어졌지만, 안타깝게도 선택된 모든 질문(그리고 몇몇 다른 제안)은 틀렸습니다.

과 같습니다.This is my 123+ test & test2. Got it?!

목표 C++ 클래스의 메서드는 다음과 같습니다.

static NSString * urlDecode(NSString *stringToDecode) {
    NSString *result = [stringToDecode stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return result;
}

static NSString * urlEncode(NSString *stringToEncode) {
    @autoreleasepool {
        NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                NULL,
                (CFStringRef)stringToEncode,
                NULL,
                (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                kCFStringEncodingUTF8
            ));
        result = [result stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];
        return result;
    }
}
NSString *str = (NSString *)CFURLCreateStringByAddingPercentEscapes(
                             NULL,
                             (CFStringRef)yourString, 
                             NULL, 
                             CFSTR("/:"), 
                             kCFStringEncodingUTF8);

또는 리스가 합니다.str네 자신.

Google은 를 Mac용 Google Toolbox에 구현합니다.그래서 저기가 그들이 그걸 하는 방법을 절정하기에 좋은 장소야.또 다른 옵션은 Toolbox를 포함하여 구현을 사용하는 것입니다.

여기서 실장을 확인해 주세요.(그것은, 사람들이 여기에 투고하고 있는 것이 바로 이것입니다.)

이게 바로 내가 이걸 빠르게 하는 방법이야.

extension String {
    func encodeURIComponent() -> String {
        return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
    }

    func decodeURIComponent() -> String {
        return self.componentsSeparatedByString("+").joinWithSeparator(" ").stringByRemovingPercentEncoding!
    }
}

Swift 5에서 한 작업은 다음과 같습니다.

func formatPassword() -> String {
    
    var output = "";

    for ch in self {

        let char = String(ch)

        switch ch {

            case " ":
                output.append("+")

                break

            case ".", "-", "_", "~", "a"..."z", "A"..."Z", "0"..."9":

                output.append(char)

                break

                default:

                print(ch)

                let unicode = char.unicodeScalars.first?.value ?? 0

                let unicodeValue = NSNumber(value: unicode).intValue

                let hexValue = String(format: "%02X", arguments: [unicodeValue])

                output = output.appendingFormat("%%%@", hexValue)

                }

            }
    
    return output as String
}

그리고 비밀번호를 정의한 함수를 호출했습니다.

//NSString 인스턴스 메서드를 다음과 같이 사용합니다.

+ (NSString *)encodeURIComponent:(NSString *)string
{
NSString *s = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return s;
}

+ (NSString *)decodeURIComponent:(NSString *)string
{
NSString *s = [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return s;
}

파라미터 값에 대해서만 부호화 또는 복호화를 수행해야 합니다.요구하는 모든 URL은 할 수 없습니다.

int strLength = 0;
NSString *urlStr = @"http://www";
NSLog(@" urlStr : %@", urlStr );
NSMutableString *mutableUrlStr = [urlStr mutableCopy];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:@":" withString:@"%3A" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:@"/" withString:@"%2F" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );

언급URL : https://stackoverflow.com/questions/8086584/objective-c-and-swift-url-encoding

반응형