2014-02-22 182 views
2

我試圖使用Objective-C編碼URL字符串

// 1. Get string 
char res = ((char)(400)); 
NSString *unencodedString = [NSString stringWithFormat:@"%c",res]; 

// 2. Encode string 
static NSString *escape = @":/?&=;[email protected]#$()',*[]"; 
NSString *result = (__bridge_transfer NSString *) 
CFURLCreateStringByAddingPercentEscapes(
             NULL, 
             (__bridge CFStringRef)unencodedString, 
             NULL, 
             (__bridge CFStringRef)escape, 
             kCFStringEncodingUTF8); 
// result = %C2%90 

編碼的URL字符串,但結果不是我期望的那樣。因爲我使用其他編程語言獲得%C6%90

正如你所看到的Objective-C結果是%C2%90,但我預計%C6%90

我的錯誤在哪裏?我做錯了什麼?

+0

什麼是您的輸入,您期望輸出什麼? –

+0

他期望輸出在所有情況下匹配@ L.B;另外,我想知道爲什麼亞歷山大是用「'417」變成「'1」的起始字符? –

+0

輸入是帶有代碼400的字符。我希望得到url編碼的字符串'%C6%C90'。將問題解除。 – Alexander

回答

2

問題是NSString *unencodedString = [NSString stringWithFormat:@"%c",res]不符合您的想法。 char res不能保存大於128的值(對於unsigned char,則爲256)。

char res = ((char)(400)); 
NSString *unencodedString = [NSString stringWithFormat:@"%c",res]; 
XCTAssertEqualObjects(unencodedString, @"\xc2\x90", @""); 

static NSString *escape = @":/?&=;[email protected]#$()',*[]"; 
NSString *result = (__bridge_transfer NSString *) 
CFURLCreateStringByAddingPercentEscapes(
             NULL, 
             (__bridge CFStringRef)unencodedString, 
             NULL, 
             (__bridge CFStringRef)escape, 
             kCFStringEncodingUTF8); 

XCTAssertEqualObjects(result, @"%C2%90", @""); 

這是一個可以工作的例子。

NSString *unencodedString = @"Ɛ"; 

static NSString *escape = @":/?&=;[email protected]#$()',*[]"; 
NSString *result = (__bridge_transfer NSString *) 
CFURLCreateStringByAddingPercentEscapes(
             NULL, 
             (__bridge CFStringRef)unencodedString, 
             NULL, 
             (__bridge CFStringRef)escape, 
             kCFStringEncodingUTF8); 
XCTAssertEqualObjects(result, @"%C6%90", @""); 

UPDATE

如果你想這樣的一個樣本工作,使用unichar-stringWithCharacters:length:

unichar res = ((unichar)(400)); 
NSString *unencodedString = [NSString stringWithCharacters:&res length:1]; 
XCTAssertEqualObjects(unencodedString, @"Ɛ", @""); 

static NSString *escape = @":/?&=;[email protected]#$()',*[]"; 
NSString *result = (__bridge_transfer NSString *) 
CFURLCreateStringByAddingPercentEscapes(
             NULL, 
             (__bridge CFStringRef)unencodedString, 
             NULL, 
             (__bridge CFStringRef)escape, 
             kCFStringEncodingUTF8); 
XCTAssertEqualObjects(result, @"%C6%90", @""); 
+0

這就是我所懷疑的。謝謝。 – Alexander

+1

@亞歷山大,我更新了我的答案,以確保能夠正常工作。 –

+0

非常感謝!檢查它,工作正確。 – Alexander