我正在使用swift向我的服务器发送消息,但是,当它结束时,我无法获得警报弹出窗口。这是密码。

func sendSimpleCommand(siteId: Int, command: String) -> Int {
    Alamofire.request(.GET, commandUrl, parameters: ["site": siteId, "command": command, "device": "ios"])
        .responseJSON { response in
            //print(response.result)   // result of response serialization

            switch response.result {
            case .Success(_):
                print("success code back from api server for command sent")
                let alertView = UIAlertController(title: "Command Sent", message: "Your \(command) has been sent.", preferredStyle: .Alert)
                let alertAction = UIAlertAction(title: "OK", style: .Default) { _ in
                }
                alertView.addAction(alertAction)
            case .Failure(_):
                print("FAIL code back from api server for command sent")
                let alertView = UIAlertController(title: "Connect Error", message: "Network error, please try again", preferredStyle: .Alert)
                let alertAction = UIAlertAction(title: "OK", style: .Default) { _ in
                }
                alertView.addAction(alertAction)
            }
    }
    return 1
}




@IBAction func startButtonTouch(sender: UIButton) {
   let helper = HelperActions()
   let site = ActiveSite.sharedInstance.siteObject
   let command: String = "start"
   sendSimpleCommand(site.id , command: command)
}

现在,当我运行它时,网络通信会正常进行,但随后我会得到一个错误,并且警报窗口永远不会出现。
不允许在视图控制器取消分配时尝试加载该视图,这可能会导致未定义的行为

最佳答案

只需在代码顶部添加这一行代码,即可对UIAlertController发出全局请求。
在swift中,我们不需要处理任何视图。敏捷的语言会帮助他们。

let alertView : UIAlertController?

删除类中alertView的所有声明
编辑
func sendSimpleCommand(siteId: Int, command: String) -> Int {
Alamofire.request(.GET, commandUrl, parameters: ["site": siteId, "command": command, "device": "ios"])
    .responseJSON { response in
        //print(response.result)   // result of response serialization

        switch response.result {
        case .Success(_):
            print("success code back from api server for command sent")
            alertView = UIAlertController(title: "Command Sent", message: "Your \(command) has been sent.", preferredStyle: .Alert)
            let alertAction = UIAlertAction(title: "OK", style: .Default) { _ in
            }
            alertView.addAction(alertAction)
        case .Failure(_):
            print("FAIL code back from api server for command sent")

            alertView = UIAlertController(title: "Connect Error", message: "Network error, please try again", preferredStyle: .Alert)
            let alertAction = UIAlertAction(title: "OK", style: .Default) { _ in
            }
            alertView.addAction(alertAction)
        }
}
return 1
}




@IBAction func startButtonTouch(sender: UIButton) {
   let helper = HelperActions()
   let site = ActiveSite.sharedInstance.siteObject
   let command: String = "start"
   sendSimpleCommand(site.id , command: command)
}

09-25 20:44