微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Swift中向用户显示网络错误消息

如何解决在Swift中向用户显示网络错误消息

问题是如何使该代码可重用,尤其是在网络方法中的错误检查和完成处理程序中的条件,以便我没有重复的代码

我创建了一个方法,该方法使用URLSession发出网络请求,并以statuscode作为参数调用完成处理程序。在完成处理中,我创建了一个条件,该条件根据状态码显示错误消息或执行测试。所有这些代码都可以使用,但是我想使其可重用,所以我没有重复的代码

联网方法

func saveMessage(data: String,day: String,completion: @escaping (Int)->()) {
    let url = URL(string: "\(Constants.baseURL)/daily_mindset/today_message")
    guard let requestUrl = url else { fatalError() }
    var request = URLRequest(url: requestUrl)
    request.httpMethod = "POST"
    
    // Set HTTP Request Header
    request.setValue("application/json",forHTTPHeaderField: "Accept")
    request.setValue("application/json",forHTTPHeaderField: "Content-Type")
    
    let jsonData = encodeJSON(with: data,day: day)
    request.httpBody = jsonData
    
    let task = URLSession.shared.dataTask(with: request) { (data,response,error) in
        if error != nil {
            completion(700)
            return
        }
        
        guard let response = response as? HTTPURLResponse else {
            completion(701)
            return
        }

        guard (200...299).contains(response.statusCode) else {
            completion(response.statusCode)
            return
        }
        
        guard let mime = response.mimeType,mime == "application/json" else {
            completion(702)
            return
        }
        
        guard let data = data else {
            completion(703)
            return
        }
        
        do {
            let todoItemmodel = try JSONDecoder().decode(MessageData.self,from: data)
            Constants.currentMindsetId = todoItemmodel._id!
            print("Response data:\n \(todoItemmodel)")
        } catch let jsonErr{
            print(jsonErr)
        }
        completion(response.statusCode)
    }
    task.resume()
}

使用完成处理程序调用联网方法

messageManager.saveMessage(data: textView.text,day: day,completion: {(statusCode: Int) -> Void in
                    if (200...299).contains(statusCode) {
                        dispatchQueue.main.async {
                            self.performSegue(withIdentifier: "ToDailyMindsetScreen",sender: sender)
                        }
                    } else if (400...499).contains(statusCode) {
                        dispatchQueue.main.async {
                            self.errorLabel.text = "Please make sure you filled in the all the required fields."
                        }
                    } else if (500...599).contains(statusCode) {
                        dispatchQueue.main.async {
                            self.errorLabel.text = "Sorry,Couldn't reach our server."
                        }
                    } else if (700...).contains(statusCode) {
                        dispatchQueue.main.async {
                            self.errorLabel.text = "Sorry,something went wrong. Try again later."
                        }
                    }
            })

我要重用的联网方法中的代码

if error != nil {
            completion(700)
            return
        }
        
        guard let response = response as? HTTPURLResponse else {
            completion(701)
            return
        }

        guard (200...299).contains(response.statusCode) else {
            completion(response.statusCode)
            return
        }
        
        guard let mime = response.mimeType,mime == "application/json" else {
            completion(702)
            return
        }
        
        guard let data = data else {
            completion(703)
            return
        }

我要重用的完成处理程序中的代码

if (200...299).contains(statusCode) {
                        dispatchQueue.main.async {
                            self.performSegue(withIdentifier: "ToDailyMindsetScreen",something went wrong. Try again later."
                        }
                    }

解决方法

如果错误消息是特定于ViewController的,则可以从创建一个基于状态代码返回消息的函数开始,如下所示:

private func getErrorMessageFor(statusCode: Int) -> String? {
    if (200...299).contains(statusCode) {
        //If no error message is returned assume that the request was a success
        return nil
    } else if (400...499).contains(statusCode) {
        return "Please make sure you filled in the all the required fields."
    } else if (500...599).contains(statusCode) {
        return "Sorry,couldn't reach our server."
    } else if (700...).contains(statusCode) {
        return "Sorry,something went wrong. Try again later."
    } else {
        return "Message for other errors?"
    }
}

您始终可以将此代码移到ViewController子类中,以提供更多通用错误消息,并在以后重写它以为特定View Controller提供更详细的错误。

class BaseViewController: UIViewController {
    func getErrorMessageFor(statusCode: Int) -> String? {
        //base implementation here
    }
}

class OtherViewController: BaseViewController {
    override func getErrorMessageFor(statusCode: Int) -> String? {
        //create a new error message only for statusCode 404
        if statusCode == 404 {
            return "The requested resource was not found on the server. Please contact the support team"
        } else {
            return super.getErrorMessageFor(statusCode: statusCode)
        }
    } 
}

请记住,随着应用程序的增长,您可能需要创建一个APIClient来为您处理网络和错误处理。看看https://bustoutsolutions.github.io/siesta/,它非常人性化

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。