ios - 无法打开 NSError

标签 ios swift mvvm option-type nserror

对于这个问题,我使用的是我的实际代码的精简版本。

该应用程序使用 MVVM 架构构建。假设有一个登录屏幕。有3个文件。

ApiClient 文件与服务器通信并获取响应。如果输入的用户名和密码匹配,它会调用 success 闭包。如果匹配失败,我将在 failure 闭包中传递自定义创建的 NSError 对象。

ApiClient.swift

import Foundation

public class ApiClient {

    public func login(#username: String, password: String, success: (data: AnyObject!) -> Void, failure: (error: NSError) -> Void) {

        if username == "isuru" && password == "123" {
            let jsonResponse = "Login Successful"
            let data = jsonResponse.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
            success(data: data!)
        } else {
            let userInfo = [
                NSLocalizedDescriptionKey: NSLocalizedString("Login Unsuccessful", comment: ""),
                NSLocalizedFailureReasonErrorKey: NSLocalizedString("Wrong Email or Password", comment: ""),
                NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString("Please Try Again", comment: "")]
            let error = NSError(domain: "AppErrorDomain", code: 1200, userInfo: userInfo)
            failure(error: error)
        }
    }
}

LoginViewModel 充当 LoginViewControllerApiClient 之间的中间人。

LoginViewModel.swift

import Foundation

protocol LoginDelegate {
    func loginCallFinished(status: Bool, error: NSError?)
}

class LoginViewModel {

    private let api = ApiClient()

    var delegate: LoginDelegate?

    init() { }

    func login(#username: String, password: String) {

        api.login(username: username, password: password, success: { (data) -> Void in
            if let delegate = self.delegate {
                delegate.loginCallFinished(true, error: nil)
            } else {
                fatalError("Have you set the LoginDelegate?")
            }
        }) { (error) -> Void in
            if let delegate = self.delegate {
                delegate.loginCallFinished(false, error: error)
            } else {
                fatalError("Have you set the LoginDelegate?")
            }
        }
    }
}

LoginViewController 中,我调用了 LoginViewModel 中的 login() 函数。响应返回到 View 模型,它调用 LoginDelegate 的函数 loginCallFinished() 并相应地传递参数值。

LoginViewController.swift

import UIKit

class LoginViewController: UIViewController, LoginDelegate {

    private let loginViewModel = LoginViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()

        loginViewModel.delegate = self

        loginViewModel.login(username: "isuru", password: "12")
    }

    // MARK: - LoginDelegate
    func loginCallFinished(status: Bool, error: NSError?) {
        if status {
            println("Login Successful!")
        } else {
            if let error = error {
                let alert = UIAlertView(title: error.localizedDescription, message: "\(error.localizedFailureReason)\n\(error.localizedRecoverySuggestion)", delegate: nil, cancelButtonTitle: "OK")
                alert.show()
            }
        }
    }
}

逻辑运行良好。我的问题发生在登录尝试失败时。如果我输入了错误的用户名或密码,它会返回我在 ApiClient 文件的 login() 函数中创建的自定义错误对象。我从 LoginViewController 检索它并在 UIAlertView 中显示错误。

if let error = error {
    let alert = UIAlertView(title: error.localizedDescription, message: "\(error.localizedFailureReason)\n\(error.localizedRecoverySuggestion)", delegate: nil, cancelButtonTitle: "OK")
    alert.show()
}

但这就是我所看到的。

enter image description here

即使我打开了 error 对象,我仍然在字符串周围得到那些 Optional() 括号。

有人知道为什么会这样吗?

谢谢。

最佳答案

您的error var 已经解包。问题是字符串 error.localizedFailureReasonerror.localizedRecoverySuggestion 没有展开。要么为它们添加一个额外的 if-let 层,要么通过像这样打印来显式地展开它们:

if let error = error {
    let alert = UIAlertView(title: error.localizedDescription, message: "\(error.localizedFailureReason!)\n\(error.localizedRecoverySuggestion!)", delegate: nil, cancelButtonTitle: "OK")
    alert.show()
}

关于ios - 无法打开 NSError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27447851/

相关文章:

ios - UITextField 数字小键盘 : dot instead of comma for float values

ios - 通过仅覆盖某些数据 Swift 3 在 Firebase 数据库中设置值

swift - CGFloat 没有转换为 UInt32?

c# - 在基类中拥有所有依赖项是一种好习惯吗?

ios - 将字符串预加载到搜索栏并从 segue 搜索

ios - 如何创建从 TableView 上的公开指示器到另一个 View Controller 的segue?

iphone - 如何在 iOS 中卸载我们的应用程序时收到通知

swift - 仅将 sizeForItemAt 应用于一个 collectionView

windows-phone-7 - 如何在 Windows Phone 中使用 Caliburn.Micro 创建 View 和 View 模型

.net - 如何从 MVVM 调用 Winforms 风格的 Invoke/Delegate?