如果您没有任何Uiview/Uicontroller?
我有一个网络框架,如果某些HTTP请求缺少某些数据,我想提出错误。
喜欢简单的uialertController或其他:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
实际上您可以在窗口上添加一个简单的标签/视图,如下:
func showNavigationAlert(text:String,backgroundColor:UIColor = kNavigationBarColor,textColor:UIColor = .white,duration:Int = 2){
let label = UILabel()
label.font = appFont(fontSize: 11)
label.textColor = textColor
label.backgroundColor = backgroundColor
label.text = text
label.textAlignment = .center
if let window = APPDELEGATE.window{
window.addSubview(label)
label.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 60)
label.center.y -= 30
UIView.animate(withDuration: 2, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: {
label.center.y += 30
}, completion: { (completed) in
UIView.animate(withDuration: 0.3, animations: {
label.center.y -= 30
}, completion: { (c) in
label.removeFromSuperview()
})
})
}
}
,在您的网络类中,只需致电
showNavigationAlert(text: parsedData["message"] as? String ?? "")
它将以更清醒的方式提醒用户,而不会使用警报烦恼,并且会自动消失。
您可以使用UIAlertView
进行此操作,尽管请注意,这已被弃用以支持UIAlertController
,因此在将来的Swift版本中不能保证它的可用性。
用法的一个示例如下:
let alert = UIAlertView(title: "Error", message: "An error occurred.", delegate: nil, cancelButtonTitle: "OK")
alert.show()
UIAlertView
上的文档可以在此处找到。