我的應用程序有時需要運行API調用到我的服務器。但是,如果用戶沒有互聯網連接,則應用程序崩潰,因爲沒有返回。我建立了一個名爲連接的函數,如果用戶有互聯網連接,則返回true。
那麼,如何利用這一點,當我運行runAPI方法,檢查連接第一,如果沒有任何比停止所有線程,並提交「沒有網絡連接」,讓用戶知道一個視圖他必須修復他/她的連接。
請記住,其他班級正在調用此類中的runAPI方法。所以說,XYZ類稱爲位於Class API中的runAPI方法。因此,如果沒有連接,我想放棄正在發生的一切,只是簡單地呈現「無互聯網連接」視圖。
func runAPI(request: String) -> NSDictionary {
return parseJSON(getJSON(request))
}
func runAPIArray(request: String) -> NSArray {
return parseJSONArray(getJSON(request))
}
func getJSON(urlToRequest: String) -> NSData{
return NSData(contentsOfURL: NSURL(string: urlToRequest))
}
func parseJSON(inputData: NSData) -> NSDictionary{
var error: NSError?
var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
return boardsDictionary
}
func parseJSONArray(inputData: NSData) -> NSArray{
var error: NSError?
var boardsArray: NSArray = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSArray
return boardsArray
}
func connection() -> Bool {
var reach = Reachability.reachabilityForInternetConnection()
var networkStatus = reach.currentReachabilityStatus()
return networkStatus != NetworkStatus.NotReachable
}
我不相信這會工作可靠,因爲您無法預測您決定停止線程(或更準確地說,線程正在執行的操作)時請求將處於什麼狀態。通常,如果出現網絡問題,請求將超時,您所要做的就是處理產生的錯誤。你最好把沒有被返回的東西當作一個合理的事件來處理,並修復崩潰。 – 2014-10-01 18:59:56
爲什麼不使用內置的NSURLConnectionDelegate方法來檢測由於下行連接導致連接何時失敗? 'connection:didFailWithError:'[link](https://developer.apple.com/library/iOS/documentation/Foundation/Reference/NSURLConnectionDelegate_Protocol/index.html#//apple_ref/occ/intfm/NSURLConnectionDelegate/connection:didFailWithError :)會給你一個錯誤,讓你知道更好一點。 [Error Codes](https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/index.html#//apple_ref/doc/uid/TP40003793-CH3g-SW40) – MZimmerman6 2014-10-01 19:20:49