2014-10-01 60 views
2

是否認真沒有一個本地URL的方式編碼查詢字符串參數的值,其中有一個「+」字符?什麼是「+」字符的iOS正確的URL編碼?

例如

[email protected]

me%2Bblah%[email protected]

我嘗試了像在其他問題中發佈的解決方案,但那些解決方案沒有正確編碼該電子郵件。

Swift - encode URL

How do I URL encode a string

一個快速的解決方案是首選,因爲這是我所是做什麼工作的,但我能夠翻譯Objective-C代碼,以SWIFT代碼大部分的。

具體而言,我正在嘗試x-www-form-urlencoded在POST請求正文中對查詢字符串值進行編碼。

+2

指定如何編碼當前*的字符串/ URL(包括應用的步驟),因爲上下文對於「+」應該,不應該,還是可能百分比編碼非常重要。 「適當的編碼」由這些規則定義,在iOS之外(以及很久之前)。 – user2864740 2014-10-01 19:59:40

+0

@ user2864740我不確定我是否理解,我給出了一個輸入示例和所需的輸出。目前,「+」字符不能與其他stackoverflow問題上提供的任何解決方案進行編碼。 – thatidiotguy 2014-10-01 20:07:11

回答

1
let email = "[email protected]" 

let output = CFURLCreateStringByAddingPercentEscapes(nil, email as NSString, nil, ":/[email protected]!$&'()*+,;=" as NSString, CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)) 

// output = "me%2Bblah%40domain.net" 

CFURLCreateStringByAddingPercentEscapes不逃避默認+@,但您可以指定它(像我一樣與其他字符一起,在":/[email protected]!$&'()*+,;="字符串)。


編輯:如果你想output成爲斯威夫特字符串:

let output = (CFURLCreateStringByAddingPercentEscapes(nil, email as NSString, nil, ":/[email protected]!$&'()*+,;=" as NSString, CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)) as NSString) as String 
+0

(我假設你的意思是「我%2Bblah%40domain.net」是你想要的輸出,而不是你輸入的「me%2blah%40 @ domain.net」。) – 2014-10-01 20:13:46

+0

你是對的,我有一個錯字,現在修好了。我會試試這個。 – thatidiotguy 2014-10-01 20:21:38

+0

嗯,這將返回一個'CFString',它顯然不想被coaxed到一個Swift'String',因爲'CFString'不是'NSString'。有任何想法嗎? – thatidiotguy 2014-10-01 20:22:53

0
println(("[email protected]" as NSString) 
    .stringByAddingPercentEncodingWithAllowedCharacters(
     NSCharacterSet.alphanumericCharacterSet())) 

輸出:

Optional("me%2Bblah%40domain%2Enet") 

在Objective-C:

NSString *encodedString = 
    ["[email protected]" stringByAddingPercentEncodingWithAllowedCharacters: 
     [NSCharacterSet alphanumericCharacterSet]]; 
+0

但是,當內容類型爲「x-www-form-urlencoded」時,不應編碼句點 – thatidiotguy 2014-10-01 20:21:22

+0

您可以向字符集添加更多字符,但它確實值得它?這些時段將被正確解碼。您被允許**編碼比您需要編碼更多的字符**。 – 2014-10-01 20:22:22