首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 多請求登錄流程的統一超時控制與錯誤碼判斷實現

     編輯:程式設計綜合問答

方案架構

登錄按鈕點擊
    │
    ▼
DispatchGroup enter() × N (N 個並發請求)
    │
    ├─► 請求 1 (用戶信息) ──► 完成 leave()
    ├─► 請求 2 (權限列表) ──► 完成 leave()
    ├─► 請求 3 (配置下發) ──► 完成 leave()
    │
    ▼
DispatchGroup notify(queue) ──► 所有成功 → 進入主頁
    │
    ├─► 超時定時器 (10s) ──► 若未 notify → 取消所有請求 → 提示超時
    │
    ▼
錯誤處理:NSError.code == -1001 (NSURLErrorTimedOut) 判斷超時

關鍵代碼

let group = DispatchGroup()
let timeoutTimer = DispatchSource.makeTimerSource(queue: .global())
timeoutTimer.schedule(deadline: .now() + 10)
timeoutTimer.setEventHandler {
    // 取消所有進行中的任務
    tasks.forEach { $0.cancel() }
    DispatchQueue.main.async { self.showTimeoutAlert() }
}
timeoutTimer.resume()

// 發起請求
func requestAPI(_ endpoint: String, completion: @escaping (Result) -> Void) {
    group.enter()
    let task = URLSession.shared.dataTask(with: URL(string: endpoint)!) { data, resp, error in
        defer { group.leave() }
        if let error = error {
            completion(.failure(error))
            return
        }
        completion(.success(data!))
    }
    task.resume()
    tasks.append(task)
}

// 等待完成
group.notify(queue: .main) {
    timeoutTimer.cancel()
    // 判斷所有結果
    if results.allSatisfy({ $0.isSuccess }) { navigateToHome() }
}

NSError Code 對照

Code常量含義
-1001NSURLErrorTimedOut請求超時
-1009NSURLErrorNotConnectedToInternet無網絡
-1011NSURLErrorBadServerResponse服務端錯誤響應

錯誤碼截圖 代碼截圖

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved