显示来自非UI类的警报

我在我的应用程序中使用Alamofire,并希望在请求出现错误(例如错误的URL)时显示警报等。

我有这个函数在一个单独的类中,因为它在应用程序的页面之间共享。

Alamofire.request(.GET, api_url) .authenticate(user: str_api_username, password: str_api_password) .validate(statusCode: 200..<300) .response { (request, response, data, error) in if (error != nil) { let alertController = UIAlertController(title: "Server Alert", message: "Could not connect to API!", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } } 

由于Alamofireasynchronous工作,我需要做错误检查然后(除非你build议否则),因为那么我想操纵结果,如果URL是错误的,那么它可以变得混乱。

毫不奇怪的

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

不起作用,所以我怎么显示这个警报?

我想说的传统方法是让任何人调用这个networking请求负责显示警报。 如果请求完成,则callback到原来的调用对象,它们负责显示警报。 其中一个原因是错误在不同的情况下可能意味着不同的事情。 您可能并不总是希望显示警报 – 这为您构build应用程序时提供了更大的灵活性。 与AlamoFire在完成时调用响应闭包的方式相同,我认为最好将它传递给在Downloader对象中发起此调用的人。

更新:你想要以与AlamoFire结构相同的方式来构build它。 您将封闭件传递给在AF请求完成时调用的AF。

你必须添加一个闭包参数到你的下载函数(参见downloadMyStuff )。 然后,一旦AF请求完成,您可以调用您之前定义的闭包( completion )。 这是一个简单的例子

 class Downloader { func downloadMyStuff(completion: (AnyObject?, NSError?) -> Void) { Alamofire.request(.GET, "http://myapi.com") .authenticate(user: "johndoe", password: "password") .validate(statusCode: 200..<300) .response { (request, response, data, error) in completion(data, error) } } } class ViewController: UIViewController { let downloader = Downloader() override func viewDidLoad() { super.viewDidLoad() self.downloader.downloadMyStuff { (maybeResult, maybeError) -> Void in if let error = maybeError { println("Show your alert here from error \(error)") } if let result: AnyObject = maybeResult { println("Parse your result and do something cool") } } } }