使用UIAlertController处理错误

时间:2016-06-25 01:56:59

标签: ios swift uialertcontroller

我有一个带有文本字段的UIAlertController,允许用户在将数据发送到服务器之前输入标题来命名文件。但是,后端可能会因为几个原因拒绝该文件,并且需要显示错误。如何在我输入文件名的同一警报控制器中显示从服务器返回的错误?

class FileController: UIViewController
{

    var alertController: UIAlertController?

    func savePressed()
    {
        createAlert()
    }

    func createAlert()
    {

        self.alertController = UIAlertController(title: "Save", message: "Name your file.", preferredStyle: .Alert)

        let saveAsPublicAction = UIAlertAction(title: "Make Public", style: .Default) { (_) in

        let fileTitle = self.alertController!.textFields![0] as UITextField

            if fileTitle.text != ""
            {
                self.initiateSave(fileTitle.text!, share: true)
            }
        }

        let saveAsPrivateAction = UIAlertAction(title: "Make Private", style: .Default) { (_) in

            let fileTitle = self.alertController!.textFields![0] as UITextField

            if fileTitle.text != ""
            {
                self.initiateSave(fileTitle.text!, share: false)
            }
        }


        let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (_) in }

        self.alertController!.addTextFieldWithConfigurationHandler { (textField) in

            NSNotificationCenter.defaultCenter().addObserverForName(UITextFieldTextDidChangeNotification, object: textField, queue: NSOperationQueue.mainQueue()) { (notification) in
            saveAsPrivateAction.enabled = textField.text != ""
            saveAsPublicAction.enabled = textField.text != ""
            }
        }

        self.alertController!.addAction(saveAsPublicAction)
        self.alertController!.addAction(saveAsPrivateAction)
        self.alertController!.addAction(cancelAction)

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


    }
}

func initiateSave(title:String?, share: Bool?)
{
     //package file
     initiatePost()

}

func initiatePost()
{
     //Send file data to server.  Receive any errors and handle
}

1 个答案:

答案 0 :(得分:1)

在您的服务器上,您可以添加更多逻辑来发送包含该信息的JSON数据。

例如:

{
    "success": true,
    "message": "Data received sucessfully"
}

如果请求成功,如果不成功:

{
    "success": false,
    "message": "There is an error"
}

因此,在解析JSON时,您将检查success是否为false,并在message键内显示错误消息。