CKError localizedDescription

折月煮酒 提交于 2019-12-30 18:56:07

问题


Aim

  • I would like to display the CKError encountered to the user in the app as an alert.
  • So I would like to extract the string from the error that can be displayed to the user.

Note: This question is not about UI code to display. Just want to extract a meaningful string from the error.

I tried to use localizedDescription but it doesn't seem to contain an appropriate string

Code:

Given below are the attempts I made:

po error  
<CKError 0x1c464cea0: "Network Unavailable" (3/NSURLErrorDomain:-1009); "The Internet connection appears to be offline.">  

po error.localizedDescription  
"The operation couldn’t be completed. (CKErrorDomain error 3.)"  

po (error as! CKError).errorUserInfo  
▿ 2 elements  
  ▿ 0 : 2 elements  
    - key : "NSUnderlyingError"  
    - value : Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={NSErrorFailingURLStringKey=https:/  
  ▿ 1 : 2 elements  
    - key : "NSDebugDescription"  
    - value : NSURLErrorDomain: -1009  



po (error as? NSError)?.localizedFailureReason  
nil  

po (error as? NSError)?.localizedRecoverySuggestion  
nil  

po (error as? NSError)?.localizedRecoveryOptions  
nil  

po (error as? NSError)?.debugDescription  
▿ Optional<String>  
  - some : "<CKError 0x1c064eaf0: \"Network Unavailable\" (3/NSURLErrorDomain:-1009); \"The Internet connection appears to be offline.\">"  

Questions:

The debug description seems to be the closest to what I want.

  1. Am I missing something ?
  2. What is the correct way to extract the error string that I can display to the user ?

回答1:


Looks like there is another error in the errorUserInfo[NSUnderlyingError]. Try getting the localizedDescription from that error.

So, that would be:

((error as? CKError)?.errorUserInfo[NSUnderlyingErrorKey] as? NSError)?.localizedDescription



回答2:


The error.localizedDescription is really all you have to work with from the error itself.

Your app can provide a better error message (more user-friendly, localized, etc.) by checking for the error code and providing its own message to the user.

(error as? NSError)?.code


来源:https://stackoverflow.com/questions/49856270/ckerror-localizeddescription

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!