UIAlertController无法被其他类调用。
UIAlertController无法被其他类调用。
我正在尝试编写一个用于解析xml的类。当出现错误时,我想显示一个警报框。
下面是我的代码:
Parse.swift
func parserXml(xmlUrl:String,completionHandler:([(staID: String, staName: String, ava: String, unava: String)]->Void)?)->Void{
self.paraserCompletionHandler = completionHandler
let request = NSURLRequest(URL: NSURL(string: xmlUrl)!)
let urlConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
urlConfig.timeoutIntervalForRequest = 30
urlConfig.timeoutIntervalForResource = 60
let urlSession = NSURLSession(configuration: urlConfig, delegate: self, delegateQueue: nil)
let task = urlSession.dataTaskWithRequest(request, completionHandler: {(data,response,error)->Void in
if error != nil{
print(error?.localizedDescription)
if (error?.code == NSURLErrorTimedOut || error?.code == NSURLErrorNotConnectedToInternet){
let vc = ViewController()
vc.alertView()
}
}else{
let parser = NSXMLParser(data: data!)
parser.delegate = self
parser.parse()
}
})
task.resume()
}
ViewController.swift
func alertView(){
var alertController = UIAlertController(title: "标题", message: "消息", preferredStyle: .Alert)
var okAction = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default)
self.presentViewController(alertController, animated: true, completion: nil)
}
当我运行我的应用程序时,应用程序崩溃并显示错误信息
fatal error: unexpectedly found nil while unwrapping an Optional value
编辑:Xcode停止在
self.presentViewController(alertController, animated: true, completion: nil)
我猜想原因是Parse.swift中调用了ViewController.swift中的alertView函数
有人可以解决这个问题吗?谢谢。
问题的出现原因是在ViewController.swift中调用了UIAlertController,但是UIAlertController不能被其他类调用。
解决方法是在Parse.swift中抛出一个自定义的异常,并在ViewController.swift中捕获它。可以创建一个自定义类(NSException),在其中建立这个异常,并将其实现到两个类中。
具体代码如下:
在Parse.swift中:
if error {
print(error?.localizedDescription)
if (error?.code == NSURLErrorTimedOut ||
error?.code == NSURLErrorNotConnectedToInternet){
[[CustomException alloc] initWithName:@"Title"
reason:@"Message"
userInfo:nil];
}
} else{
let parser = NSXMLParser(data: data!)
parser.delegate = self
parser.parse()
}
在ViewController.swift中:
catch (YourCustomException *ce) {
alertController = UIAlertController(title: ce.name,
message: ce.message,
preferredStyle: .Alert)
}
这样,在ViewController中调用parserXml(...)时,可以使用try()来捕获异常,在catch()中给出警告弹窗。这样的话,如果在parserXml(...)中抛出多个异常,就可以显示多个错误类型的弹窗了。
以上是一种解决方法,希望能对你有所帮助。