我正在運行來自 stackoverflow 的類似問題的代碼,以便在 xcode playground 上只對所有特殊字符(@!#$%^&*()~-_= ;:'/.,<>{}[])進行百分比編碼(不對字母數字字符編碼)。 以下是我的嘗試
import UIKit
//////////////
/Attempt 1
var originalString = "Test@123!#$%^&*()~-_= ; :'/.,<>{}[]"
let escapedString = originalString.addPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllallowed)
print("Attemp 1:"/span>,escapedString)
///////////////////。
/Attempt 2
func encodeValue(_ string: String) -> String? {
guard let unescapedString = string.addPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: ":/").inverted) else { return nil }
return unescapedString
}
let encodedString = encodeValue("Test@123!#$%^&*()~-_= ;:'/。,<>{}[]")
print("Attemp 2:"/span>,encodedString)
//////////////////////。
/Attemp 3
extension String {
var encoded: String? {
return self.addPercentEncoding(withAllowedCharacters: .urlHostAllowed)
}
}
let encodedUrl = "Test@123!#$%^&*()~-_= ;:'/。,<>{}[]".encoded
print("Attemp 3:"/span>,encodedUrl)
//////////////。
/Attemp 4
let myurlstring = "Test@123!#$%^&*()~-_= ; :'/.,<>{}[]"
let urlwithPercentEscapes = myurlstring.additionPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
print("Attemp 4:", urlwithPercentEscapes)
//////////////。
//Attempt 5。
var s = "Test@123!#$%^&*()~-_= ; :'/.,<>{}[]"
let encodedLink = s.addPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)
let encodedURL = NSURL(string: encodedLink! )! as URL
print("Attemp 5:", encodedURL)
下面是結果
Attemp 1: Optional("Test@123!#$%^&*()~-_= ;:'/.,<>{}[]")
Attemp 2: Optional("Test@123!#$%^&*()~-_= ;:'/.,<>{}[]")
Attemp 3: Optional("Test@123!#$%^&*()~-_= ;:'/.,<>{}[]")
Attemp 4: Optional("Test@123!#$%^&*()~-_= ;:'/.,<>{}[]")
Attemp 5: Test@123!#$%^&*()~-_= ;:'/.,<>{}[]
他們中沒有人對完整的特殊字符進行編碼,我想對所有的特殊字符進行編碼,就像在幾乎所有的嘗試中都沒有對以下特殊字符進行編碼一樣。
*()~-_= ; :'/.,
請告訴我對我所有的特殊字符進行百分比編碼的代碼,包括*()~-_= ;:'/。
uj5u.com熱心網友回復:
要對除字母數字以外的所有內容進行百分比編碼,請將.alphanumerics作為允許的字符:
let encoded = s.addPercentEncoding(withAllowedCharacters: .alphanumerics)。
對于你的例子,這將回傳(作為一個可選):
Test@123!#$%^&*()~-_=+;:'/.,<>{}[]
我想這就是你要找的。
這并不特別有用,因為這不太可能正確編碼任何特定的URL(這似乎是你正在做的事情)。但是如果你有你所描述的需求(這與正確編碼 URL 無關),那么你就應該這樣做。
如果您想對 URL 進行正確編碼,請使用 URLComponents 來構建 URL。它將使用每一塊的規則對該塊進行編碼。沒有簡單的字串替換可以正確地對URL進行百分比編碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/307971.html
標籤:
