swift在UIAlertController中显示错误消息数组

时间:2016-04-10 19:06:26

标签: ios swift uialertcontroller

我想知道是否可以在UIAlertController中显示错误消息。

我的服务器将错误消息作为JSON发回。

我可以使用以下方式获取每条错误消息:

if let errorVal = errorVal {

    if let items = errorVal["errors"].array {
        for item in items {
            print(item)
        }
    }


}

现在我想知道如何在AlertController中显示错误。 AlertController的message参数需要一个字符串,但我的错误是JSON然后转换为.array

let alertController = UIAlertController(title: "Hey! :)", message: "My Errors", preferredStyle: .Alert)

let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)

alertController.addAction(defaultAction)

self.presentViewController(alertController, animated: true, completion: nil)

1 个答案:

答案 0 :(得分:1)

好吧,你可以建立一个字符串,其中包含每个错误(或只是消息)的描述,并显示(可能显示太多)。它会是这样的:

var errorMessages = ""
if let errorVal = errorVal {
    if let items = errorVal["errors"].array {
        for item in items {
            print(item)
            errorMessages = errorMessages + item + "\n" // if this is NSError you can use description, message or code
        }
    }
}

以后你可以做类似的事情:

let alertController = UIAlertController(title: "Hey! :)", message: errorMessages , preferredStyle: .Alert)

let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)

alertController.addAction(defaultAction)

self.presentViewController(alertController, animated: true, completion: nil)
相关问题