在ISO-8859-1中编码NSURL [英] encoding NSURL in ISO-8859-1
问题描述
我有一个包含TextFields的ViewController,我需要将这些值发送到专用的HTTP服务。
我主要担心的是编码类型,因为这个应用程序是法语版,可能包含一些重音符号('é','è'等等...)但我还需要正确格式化我的字段,因为它也可能包含空格....
I have a ViewController containing TextFields and I would need to send those values to a dedicated HTTP service. My main concern comes from the encoding type, as this app is in French and may contain some accents ('é', 'è', etc,...) but also I need to format correctly my fields as it may contain spaces as well....
我尝试使用不同的方法,但我在服务器端仍然有错误的编码。
I tried to use different ways but I still have a wrong encoding on the server side.
这是我的代码示例:
let url_to_request = "http://11.22.33.44:8080/SRV/addRepertoire"
var params = "owner=\(User.sharedInstance.email)&adresse=\(adresse.text!)&nom=\(nom.text!)&telephone=\(telephone.text!)&commentaires=\(commentaires.text!)"
//trying to encode in ISO-8859-1
let dt = NSString(CString: params, encoding: NSISOLatin1StringEncoding)
//preparing string to be used in a NSURL
let final_url = dt!.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
print("URL loadRepertoire: \(url_to_request+"?"+final_url!)")
例如,字段nom包含bébé,其编码为b%C4%82%C5%A0b%C4%82%C5%A0,而我的服务器期待b%E9b%E9
for instance, field "nom" contains "bébé" which is encoded "b%C4%82%C5%A0b%C4%82%C5%A0" whereas my server is expecting "b%E9b%E9"
EDIT2:
我试图使用以下内容:
let url_to_request = "http://11.22.33.44:8080/SRV/addRepertoire"
let params = "owner=\(User.sharedInstance.email)&adresse=\(adresse.text!)&nom=\(nom.text!)&telephone=\(telephone.text!)&commentaires=\(commentaires.text!)"
let tmp_url = url_to_request + "?" + params
let final_url = tmp_url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
print("URL addRepertoire: \(final_url)")
但结果仍然是:
b%C3%83%C2%A9b%C3%83%C2%A9, diplayed bébé instead of bébé
推荐答案
stringByAddingPercentEncodingWithAllowedCharacters
总是使用UTF-8表示,所以我担心你可能需要自己动手。
stringByAddingPercentEncodingWithAllowedCharacters
always uses UTF-8 representation, so I'm afraid you may need to do it yourself.
extension String {
func stringByAddingPercentEncodingForISOLatin1() -> String? {
let allowedCharacterSet = NSCharacterSet(charactersInString:
"0123456789"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz"
+ "_-.~"
+ "=&" //You'd better remove this and encode each param.
)
if let data = self.dataUsingEncoding(NSISOLatin1StringEncoding) {
var result = ""
for i in 0..<data.length {
let ch = UnsafePointer<UInt8>(data.bytes)[i]
if ch >= 0x80 || !allowedCharacterSet.characterIsMember(unichar(ch)) {
result += String(format: "%%%02X", ch)
} else {
result.append(UnicodeScalar(ch))
}
}
return result
} else {
return nil
}
}
}
"bébé".stringByAddingPercentEncodingForISOLatin1()! //->"b%E9b%E9"
这篇关于在ISO-8859-1中编码NSURL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!