I think you are missing the correct approach.
You don't need to localise low level network error as:
- are generally useless to final user
- are handy to develop, not to be shown (you can eventually log them..)
- when you got a code, change it in a readable generic message, and THEN localise it.
For III point:
final private func downloadMyData(){
guard let myURL = URL(string: "__https://ingconti.com/wrongurl") else{
return
}
let session = URLSession.shared
let task = session.dataTask(with: myURL) { (data: Data?, response: URLResponse?, error: Error?) in
// session cannot be created...
if let error = error {
self.manageLowLevel(error: error)
return
}
var statusCode: Int = 0
if let httpResponse : HTTPURLResponse = response as? HTTPURLResponse{
statusCode = httpResponse.statusCode
}
if 200 ... 299 ~= statusCode {
self.parse(data: data)
}else{
self.manageHTTPError(code: statusCode, data: data)
}
}
task.resume()
}
If you got a BIG error (for example in my code I used a wrong prefix, "__https")
You will get _code = -1022,
and You can manage this way:
final private func manageLowLevel(error: Error){
#if DEBUG
print(error)
#endif
var msg = ""
let code = error._code
switch code {
case -1002:
msg = localized("GENERIC_NETWORK_ERR")
default:
msg = localized("GENERIC_NETWORK_ERR")
}
// display msg... (on MAIN THREAD...)
}
func localized(_ msg: String)->String{
let s = NSLocalizedString(msg, comment : "")
return s
}
Where You can mask out message to final user and make it more general (and localised using a convenience function "localized")
For HTTP error (for example not found resource... i.e. "https://ingconti.com/wrongurl") You will get error 404 in http/s.
So you can do similar:
final private func manageHTTPError(code: Int, data : Data?){
guard let data = data else{
return
}
#if DEBUG
if let s = String(data: data, encoding: .utf8){
print(s)
}else{
if let s = String(data: data, encoding: .ascii){
print(s)
}
}
#endif
var msg = ""
switch code {
case 404:
msg = localized("NETWORK_CODE_404")
default:
msg = localized("GENERIC_NETWORK_ERR")
}
// display msg...
}
Or even merged toghether.
(string s in
#if DEBUG
if let s = .....
will show server error, and again do not show to user...)
to sum up:
so not show low level error, see gentle message, so for example in you localized strings You can have:
"GENERIC_NETWORK_ERR" = "Network error";
"NETWORK_CODE_404". = "Network error (no data)";
and in spanish...
"GENERIC_NETWORK_ERR" = "error de red ";
...
Hope it can help.