我最近開始進行 iOS 開發,目前正在為現有應用程式添加新功能。對于此功能,我需要JSON從 Web 服務器獲取檔案。但是,如果服務器無法訪問(沒有互聯網/服務器不可用等),則JSON需要使用本地服務器。
在我當前的實作中,我嘗試使用do catch塊,但如果沒有互聯網連接,應用程式只是掛起而不是進入catch塊。JSON決議和本地資料讀取似乎作業正常,問題可能出在GET方法中,因為我試圖定義一個回呼以將JSON資料作為單獨的變數回傳,但我不確定這是否是正確的方法。
處理這種情況的最佳方法是什么?
let url = URL(string: "https://jsontestlocation.com") // test JSON
do {
// make a get request, get the result as a callback
let _: () = getRemoteJson(requestUrl: url!, requestType: "GET") {
remoteJson in
performOnMainThread {
self.delegate.value?.didReceiveJson(.success(self.parseJson(jsonData: remoteJson!)!))
}
}
}
catch {
let localFile = readLocalFile(forName: "local_json_file")
let localJson = parseJson(jsonData: localFile!)
if let localJson = localJson {
self.delegate.value?.didReceiveJson(.success(localJson))
}
}
getRemoteJson() 執行:
private func getRemoteJson(requestUrl: URL, requestType: String, completion: @escaping (Data?) -> Void) {
// Method which returns a JSON questionnaire from a remote API
var request = URLRequest(url: requestUrl) // create the request
request.httpMethod = requestType
// make the request
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
// check if there is any error
if let error = error {
print("GET request error: \(error)")
}
// print the HTTP response
if let response = response as? HTTPURLResponse {
print("GET request status code: \(response.statusCode)")
}
guard let data = data else {return} // return nil if no data
completion(data) // return
}
task.resume() // resumes the task, if suspended
}
parseJson() 執行:
private func parseJson(jsonData: Data) -> JsonType? {
// Method definition
do {
let decodedData = try JSONDecoder().decode(JsonType.self, from: jsonData)
return decodedData
} catch {
print(error)
}
return nil
}
uj5u.com熱心網友回復:
func NetworkCheck() -> Bool {
var isReachable = false
let reachability = Reachability()
print(reachability.status)
if reachability.isOnline {
isReachable = true
// True, when on wifi or on cellular network.
}
else
{
// "Sorry! Internet Connection appears to be offline
}
return isReachable
}
在您的 API 請求之前呼叫 NetworkCheck()。如果它回傳 false,請讀取您的本地 json 檔案。如果為真,則執行遠程 API 呼叫。
Incase 遠程 API 呼叫后,任何失敗檢查與 HTTP 標頭回應代碼。
如果讓 httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
}
uj5u.com熱心網友回復:
我認為您需要在等待回應時停止請求掛起。應用程式可能在連接不良的情況下運行,并且能夠獲取一些但不是全部資料,在這種情況下,您可能希望故障轉移到本地 JSON。
我認為您可以大致使用您擁有的內容,但在 URLSession 上添加超時配置,如下所述:https ://stackoverflow.com/a/23428960/312910
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/346114.html
