在 VC 上显示 AlertView。当 custom class 在闭包中捕捉到错误
Show AlertView on VC. When custom class catches the error in closure
我想问一下关于新的 UIAlertController 的问题。如何检测自定义 class 上的错误以向用户显示警报视图?我想在 switch case 变为默认语句时执行我的警报视图。我的 NetworkOperation class 是自定义的 class,带有用于从网络下载一些 JSON 数据的闭包。
class NetworkOperation {
lazy var config: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
lazy var session: NSURLSession = NSURLSession(configuration: self.config)
let mainURL: NSURL
typealias JSONWeatherDataDictionary = ([String: AnyObject]?) -> Void
init(url: NSURL) {
mainURL = url
}
func downloadWeatherDataFromWeb(completion: JSONWeatherDataDictionary) {
let request = NSURLRequest(URL: mainURL)
let dataTask = session.dataTaskWithRequest(request) {
(let data, response, error) in
if let httpResponse = response as? NSHTTPURLResponse {
switch httpResponse.statusCode {
case 200:
// HTTP Response success use the weather data !
do {
let weatherDataDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? [String: AnyObject]
completion(weatherDataDictionary)
} catch {
print("Data can't get")
}
default:
// I want to execute my alert view in there. showAlertView()
print("Http Response failed with this code: \(httpResponse.statusCode)")
}
} else {
print("HTTP Response convert fail !")
}
}
dataTask.resume()
}
}
如果执行默认情况,如何在视图控制器中查看我的警报视图?我试图用 UIAlertViewDelegate 解决这个问题,但它已被弃用 iOS9 所以我想学习解决这个问题的最佳常用方法。
谢谢大家...
如果您想做的只是显示一个警告让用户知道错误,并提供一个取消按钮以关闭该按钮,您可以使用 UIAlertController
.
我用 HTTP URL 测试了以下代码,导致它失败,弹出警报视图显示 status code
;并在点击 "cancel" 按钮后自行关闭。
func downloadWeatherDataFromWeb(completion: JSONWeatherDataDictionary)
{
let request = NSURLRequest(URL: mainURL)
let dataTask = session.dataTaskWithRequest(request)
{
(let data, response, error) in
if let httpResponse = response as? NSHTTPURLResponse
{
switch httpResponse.statusCode
{
case 200:
do
{
let weatherDataDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? [String: AnyObject]
completion(weatherDataDictionary)
}
catch
{
print("Could not retrieve data")
}
default:
print("Http Response failed with the following code: \(httpResponse.statusCode)")
let alert = UIAlertController(title: "HTTP Error", message:String(httpResponse.statusCode), preferredStyle: UIAlertControllerStyle.Alert)
//set up cancel action
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel)
{
action -> Void in
//should you want to carry some other operations upon canceling
}
//add the action
alert.addAction(cancelAction)
dispatch_async(dispatch_get_main_queue(),
{
self.presentViewController(alert, animated:true, completion:
{
//alert controller presented
})
})
}
}
else
{
print("HTTP Response conversion failed!")
}
}
dataTask.resume()
}
更新:回应您的评论
请添加一个UIViewController
变量:
class NetworkOperation
{
var viewController : UIViewController = UIViewController()
....
并对上面的default:
案例进行修改:
dispatch_async(dispatch_get_main_queue(),
{
self.addChildViewController(self.viewController)
self.view.addSubview(self.viewController.view)
self.viewController.didMoveToParentViewController(self)
self.viewController.presentViewController(alert, animated:true,
completion:
{
//alert controller presented
})
})
我刚才冒昧地测试了一下;它弹出并关闭。
另一个更新:
然后,我们可以执行以下操作:
dispatch_async(dispatch_get_main_queue(),
{
let topViewController = UIApplication.sharedApplication().keyWindow?.rootViewController
topViewController!.presentViewController(alert, animated:true,
completion:
{
//alert controller presented
})
})
我想问一下关于新的 UIAlertController 的问题。如何检测自定义 class 上的错误以向用户显示警报视图?我想在 switch case 变为默认语句时执行我的警报视图。我的 NetworkOperation class 是自定义的 class,带有用于从网络下载一些 JSON 数据的闭包。
class NetworkOperation {
lazy var config: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
lazy var session: NSURLSession = NSURLSession(configuration: self.config)
let mainURL: NSURL
typealias JSONWeatherDataDictionary = ([String: AnyObject]?) -> Void
init(url: NSURL) {
mainURL = url
}
func downloadWeatherDataFromWeb(completion: JSONWeatherDataDictionary) {
let request = NSURLRequest(URL: mainURL)
let dataTask = session.dataTaskWithRequest(request) {
(let data, response, error) in
if let httpResponse = response as? NSHTTPURLResponse {
switch httpResponse.statusCode {
case 200:
// HTTP Response success use the weather data !
do {
let weatherDataDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? [String: AnyObject]
completion(weatherDataDictionary)
} catch {
print("Data can't get")
}
default:
// I want to execute my alert view in there. showAlertView()
print("Http Response failed with this code: \(httpResponse.statusCode)")
}
} else {
print("HTTP Response convert fail !")
}
}
dataTask.resume()
}
}
如果执行默认情况,如何在视图控制器中查看我的警报视图?我试图用 UIAlertViewDelegate 解决这个问题,但它已被弃用 iOS9 所以我想学习解决这个问题的最佳常用方法。 谢谢大家...
如果您想做的只是显示一个警告让用户知道错误,并提供一个取消按钮以关闭该按钮,您可以使用 UIAlertController
.
我用 HTTP URL 测试了以下代码,导致它失败,弹出警报视图显示 status code
;并在点击 "cancel" 按钮后自行关闭。
func downloadWeatherDataFromWeb(completion: JSONWeatherDataDictionary)
{
let request = NSURLRequest(URL: mainURL)
let dataTask = session.dataTaskWithRequest(request)
{
(let data, response, error) in
if let httpResponse = response as? NSHTTPURLResponse
{
switch httpResponse.statusCode
{
case 200:
do
{
let weatherDataDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? [String: AnyObject]
completion(weatherDataDictionary)
}
catch
{
print("Could not retrieve data")
}
default:
print("Http Response failed with the following code: \(httpResponse.statusCode)")
let alert = UIAlertController(title: "HTTP Error", message:String(httpResponse.statusCode), preferredStyle: UIAlertControllerStyle.Alert)
//set up cancel action
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel)
{
action -> Void in
//should you want to carry some other operations upon canceling
}
//add the action
alert.addAction(cancelAction)
dispatch_async(dispatch_get_main_queue(),
{
self.presentViewController(alert, animated:true, completion:
{
//alert controller presented
})
})
}
}
else
{
print("HTTP Response conversion failed!")
}
}
dataTask.resume()
}
更新:回应您的评论
请添加一个UIViewController
变量:
class NetworkOperation
{
var viewController : UIViewController = UIViewController()
....
并对上面的default:
案例进行修改:
dispatch_async(dispatch_get_main_queue(),
{
self.addChildViewController(self.viewController)
self.view.addSubview(self.viewController.view)
self.viewController.didMoveToParentViewController(self)
self.viewController.presentViewController(alert, animated:true,
completion:
{
//alert controller presented
})
})
我刚才冒昧地测试了一下;它弹出并关闭。
另一个更新:
然后,我们可以执行以下操作:
dispatch_async(dispatch_get_main_queue(),
{
let topViewController = UIApplication.sharedApplication().keyWindow?.rootViewController
topViewController!.presentViewController(alert, animated:true,
completion:
{
//alert controller presented
})
})