Created
January 20, 2025 00:51
-
-
Save dolphinsue319/d5e137fdf69e257f52df5298ef04e7f8 to your computer and use it in GitHub Desktop.
測速網域並儲存的物件
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
// 測速網域的物件 | |
class DomainSpeedTester { | |
// 用來儲存測試結果的內部資料結構 | |
private var results: [(domain: String, time: Double)] = [] | |
// 請求圖片的 function,圖片不需儲存,最後回傳下載時間 (ms) | |
func downloadImg(domain: String) async throws -> Double { | |
let urlString = "https://\(domain)/test-img" | |
guard let url = URL(string: urlString) else { | |
throw URLError(.badURL) // 拋出錯誤表示 URL 無效 | |
} | |
let startTime = Date() // 記錄開始時間 | |
do { | |
let (_, response) = try await URLSession.shared.data(from: url) | |
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { | |
throw URLError(.badServerResponse) // 拋出錯誤表示下載失敗 | |
} | |
let endTime = Date() // 記錄結束時間 | |
let elapsedTime = endTime.timeIntervalSince(startTime) * 1000 // 轉換為毫秒 | |
return elapsedTime | |
} catch { | |
throw error // 拋出發生的錯誤 | |
} | |
} | |
// 儲存結果的 function | |
func set(domain: String, time: Double) { | |
results.append((domain: domain, time: time)) | |
results.sort { $0.time < $1.time } // 按下載時間排序 | |
} | |
// 清除所有結果的 function | |
func clear() { | |
results.removeAll() | |
} | |
// 取出結果的 function | |
func get() -> Data? { | |
let jsonResults = results.map { ["domain": $0.domain, "time": Int($0.time)] } | |
return try? JSONSerialization.data(withJSONObject: jsonResults, options: .prettyPrinted) | |
} | |
} | |
// 使用範例 | |
@main | |
struct Main { | |
static func main() async { | |
let tester = DomainSpeedTester() | |
let domains = ["a.com", "b.com", "c.com"] | |
tester.clear() | |
print("結果已清除。") | |
for domain in domains { | |
do { | |
let time = try await tester.downloadImg(domain: domain) | |
tester.set(domain: domain, time: time) | |
} catch { | |
print("無法下載 \(domain): \(error)") | |
} | |
} | |
if let jsonData = tester.get(), let jsonString = String(data: jsonData, encoding: .utf8) { | |
print("測速結果:\n\(jsonString)") | |
} else { | |
print("無法取得測速結果。") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment