2016-02-05 61 views
0

我使用下面的方法來編碼目標字符串 - C:字符串編碼 - 斯威夫特

+(NSString*)urlEncoded:(NSString*)string 
{ return ((NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes (NULL,(CFStringRef)string, NULL,(CFStringRef)@"! '=();@&+$%#",kCFStringEncodingUTF8)));} 

是否有在雨燕2.0這種方法的任何對手?我嘗試過使用堆棧中的很多解決方案,但他們都不能解決我的問題。

回答

2

你可能想使用stringByAddingPercentEncodingWithAllowedCharactersNSCharacterSet的URL組分特定的字符集:

let title = "NSURL/NSURLComponents" 
let escapedTitle = title.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) 

這些人物背後的想法將是,他們很可能因爲他們比任何有限的描述使用更正確設定你有。也就是說,您可以使用與自己生成的設置相同的方法:

let escapeSet = NSCharacterSet(charactersInString: "! '=();@&+$%#") 
let string = "sdfT&*w5e#sto([+peW7)%y9pqf])" 
let escapedString = string.stringByAddingPercentEncodingWithAllowedCharacters(escapeSet.invertedSet) 
// "sdfT%26*w5e%23sto%28[%2BpeW7%29%25y9pqf]%29" 
+0

不工作。我的字符串是「sdfT&* w5e#sto([+ peW7)%y9pqf])」。我想編碼這個。 –

+0

@VamshiKrishna:更新! –

+0

它工作。但有一個小小的更新。通過「!'=()[]; @&+ $%#」替換「!'=(); @&+ $%#」。謝謝 –