如何处理 NSData contentsOfURL EXC_BREAKPOINT 错误

How to deal with NSData contentsOfURL EXC_BREAKPOINT error

我正在尝试使用 contentsOfURL 从服务器获取 NSData。当 iPhone 连接到 wifi 时,它工作正常。但是当没有连接到 wifi 时,我的应用程序崩溃并显示 EXC_BREAKPOINT 消息。如何处理或规避未连接时崩溃的问题?

do {
    let varOption = try NSData(contentsOfURL: NSURL(string: urlToRequest)!, options:NSDataReadingOptions.DataReadingMappedIfSafe)
} catch {
    print("error encountered")
}

是否有使用 NSDatacontentsOfURL 的要求?为什么不使用 NSURLSession 发出异步 Web 请求?

NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlToRequest)!) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
    // if data && !error, do the thing
}.resume()

您可以使用本教程创建一个函数来检查 iPhone 是否已连接到 Internet。

http://www.brianjcoleman.com/tutorial-check-for-internet-connection-in-swift/

实现此函数后,您可以使用它来验证连接,然后将您的代码放入 if 语句块

if isConnectedToNetwork() {   //<-- This is the function implemented in tutorial posted before.

    //Here we put your code
    do {
        let varOption = try NSData(contentsOfURL: NSURL(string: urlToRequest)!, options:NSDataReadingOptions.DataReadingMappedIfSafe)
    } catch {
        print("error encountered")
    }

}