2012-12-20 55 views
0

可能重複:
URL encode a NSString如何通過AFNetworking客戶端發送帶有空格的字符串?

我想與像空格字符串發送:

stack exchange 

通過

[[ApiClient sharedClient] getPath:[NSString stringWithFormat:@"/search/?q=%@", @"stack exchange"] parameters:nil success:^ ... 

但我越來越

Error Domain=NSURLErrorDomain Code=-1000 "bad URL" 

我該如何解決這個問題?

+2

你需要URL編碼字符串... http://stackoverflow.com/questions/8088473/url-encode-a-nsstring –

回答

0

您將要編碼您的url參數。

// Add this to your class or universal class to be used 
// Encode a string to embed in an URL. 
NSString *encodeToPercentEscapeString(NSString *string) { 
    return (__bridge NSString *) 
    CFURLCreateStringByAddingPercentEscapes(NULL, 
              (CFStringRef) string, 
              NULL, 
              (CFStringRef) @"!*'();:@&=+$,/?%#[]", 
              kCFStringEncodingUTF8); 
} 

// now you can encode your parameters before adding to your url 
NSString *urlParam = @"My custom text"; 

urlParam = encodeToPerecentEscapeString(urlParam); 

// now you can use urlParam in any url parameter requirement 
0

前段時間我做了一個示例項目,顯示了您可以在ObjC中轉義字符串的不同方式。這是on github

最後我用這樣的:

NSString *escapedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef) myString, NULL, CFSTR("!*()$&`:<>[]{}\"+#@/;=?\\^|~'%%,."), kCFStringEncodingUTF8)); 

這似乎涵蓋所有的邊緣情況下,我能找到。

相關問題