2016-01-13 78 views
1

我想从使用contentsOfURL的服务器获取NSData。当iPhone连接到WiFi时,它工作正常。但是,如果没有连接到无线网络,我的应用会崩溃,并显示EXC_BREAKPOINT消息。如何处理或规避未连接时发生崩溃的问题?如何处理NSData contentsOfURL EXC_BREAKPOINT错误

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

enter image description here

+0

是'urlToRequest'零里面? – JAL

+0

嗨日航。感谢你的想法。不。如果wifi连接,这个代码工作正常。 IE浏览器,urltorequest不会突然成为零当wifi没有连接 –

回答

2

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

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

如果我理解正确,反正NSData contentsOfURL弃用。 NSURLSession工作得很好。谢谢。 –

1

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

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

实现这个功能,你可以用它来验证的连接,然后后把你的代码如果语句块

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") 
    } 

}