I am writing some code to parse korean text from server encoded with euc-kr
korean encoder.
When I just do the same encoding in Python, it works as expected. But when I do it as following, encoding doesn't work. The result is unreadable.
In Python :
string = u'안녕하세요.'.encode('eucKR')
In Swift :
let encoding:UInt = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(
CFStringEncodings.EUC_KR.rawValue))
let encodedData = "안녕하세요.".data(using: String.Encoding(rawValue: encoding))!
What the difference between those 2 encodings ?
Following are full source codes for both python and swift. I still stuck on the encoding part. Is the problem related to alamofire post request?
Python:
import requests
from pattern import web
string = u'저는 내일 바빠서 학교에 못갑니다.'.encode('eucKR')
r = requests.post("http://nlp.korea.ac.kr/~demo/dglee/komatag.php", data={'formradio1': '', 'formradio2': 'ems', 'textarea': string})
dom = web.Element(r.text)
main = dom('tr')
for item in main:
result = web.plaintext(item.source)
a = result.encode('ISO-8859-1')
t=a.decode('eucKR')
print(t)
Swift:
override func viewDidLoad() {
let string: NSString = NSString(string: "안녕하세요")
let encodedEucKr = stringToEuckrString(stringValue: string as String)
print(encodedEucKr)
Alamofire.request("http://nlp.korea.ac.kr/~demo/dglee/komatag.php", method: .post, parameters: ["formradio1":"", "formradio2":"ems", "textarea": encodedEucKr], headers: nil).responseString { response in
switch(response.result) {
case .success(_):
if let data = response.result.value{
print(response.result.value)
}
break
case .failure(_):
print(response.result.error)
break
}
}
}
func stringToEuckrString(stringValue: String) -> String {
let encoding:UInt = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(
CFStringEncodings.EUC_KR.rawValue))
let encodedData = stringValue.data(using: String.Encoding(rawValue: encoding))!
let attributedString = try? NSAttributedString(data: encodedData, options:[:], documentAttributes: nil)
if let _ = attributedString {
return attributedString!.string
} else {
return ""
}
}
It was not easy for two reasons...
Sending form data in EUC-KR is not considered to be standard-compliant in modern web technologies and standards.
The response sent from your server is sort of broken, in that Swift cannot decode the result as a valid EUC-KR text.
(This seems to be a bug of your server side code.)
Anyway, when you need to send a web form based request to your server in EUC-KR:
Some details depend on the server. I have never used Alamofire, so I do not know if Alamofire supports such things.
Here I show you an example using a normal
URLSession
:If your server side can handle UTF-8 requests and responses properly, the code above can be far more simple. Using EUC-KR in web services is sort of outdated. You'd better adopt UTF-8 soon.