登錄按鈕點擊
│
▼
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() }
}
| Code | 常量 | 含義 |
|---|---|---|
| -1001 | NSURLErrorTimedOut | 請求超時 |
| -1009 | NSURLErrorNotConnectedToInternet | 無網絡 |
| -1011 | NSURLErrorBadServerResponse | 服務端錯誤響應 |
