简体   繁体   English

在Swift上捕获错误,并在View Controller上显示警告

[英]Catch error on Swift and show it on View Controller with an alert

I am developing an application for IOS with Swift, and at some point run the line: 我正在使用Swift开发用于IOS的应用程序,并在某些时候运行该行:

let myURLString = "http://FILE URL"
var myHTMLString:NSString = ""
if let myURL = NSURL(string: myURLString) {
    var error: NSError?
    myHTMLString = NSString(contentsOfURL: myURL, encoding: NSUTF8StringEncoding, error: &error)!

    if let error = error {
        var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
        println("Error : \(error)")
    }
    else {
        println("HTML : \(myHTMLString)")
    }
}
else {
    println("Error: \(myURLString) doesn't seem to be a valid URL")
}
return myHTMLString as String

This returns a String. 这将返回一个字符串。

If the device (or the Mac while working with XCode) do not have Internet, the application fails because: 如果设备(或使用XCode的Mac机)没有Internet,则该应用程序将失败,原因是:

        myHTMLString = NSString(contentsOfURL: myURL, encoding: NSUTF8StringEncoding, error: &error)!

is null (nil) 为空(无)

My question is: How can I catch this error, execution continues, and display an error message in the View Controller? 我的问题是:如何捕获此错误,继续执行并在View Controller中显示错误消息?

Return myHTMLString as a String? 返回myHTMLString作为字符串? optional instead of the String. 可选,而不是字符串。 Once the calling application gets back the myHTMLString variable, check for nil 一旦调用应用程序获取了myHTMLString变量,请检查nil

    if let htmlString = myHTMLString{
         // HTML String returned by function isnt nil
    }
    else {
         // HTML String returned by function is nil. Handle the error
    } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM