2016-03-22 11 views
0

私はユーザーが任意のテキストを入力できる画面を作成しています。テキストを有効なURLに変換する必要があります。文字列に文字列をURL objective-Cに変換します

- (NSString *)urlencode { 
    NSMutableString *output = [NSMutableString string]; 
    const unsigned char *source = (const unsigned char *)[self UTF8String]; 
    int sourceLen = strlen((const char *)source); 
    for (int i = 0; i < sourceLen; ++i) { 
     const unsigned char thisChar = source[i]; 
     if (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; 
} 

例を 1 CFURLCreateStringByAddingPercentEscapes

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

2.カテゴリー::私は、スタックオーバーフローの質問の多くに見ていると、彼らはだますソリューションが出ているユーザーが手動で入れた場合空白の代わりにテキストに必要な%20(たとえば)を置き、上記のいずれかのソリューションを使用すると、%20は%25に変換されます。

問題を解決する方法を教えてもらえますか?

答えて

0

%%20が所望の出力である、%2520にURLエンコードされ、実際に、%25にURLエンコードされるため。

%20をユーザー入力に保ちたい場合は、%20のすべてを1つの空白に置き換えて、置き換えられた文字列をurlencodedできます。

+0

これは単なる例です。私は他の人をどのように扱いますか?そのようなセナロを処理し、文字列を有効なURLに変換するには、とにかくありますか? –

関連する問題