我正在创建一个Xcode命令行实用程序应用程序,该应用程序应从JSON文件读取URL,并检查每个URL以查看其是否返回200 HTTP代码。到目前为止,我已经知道了:
Services.shared.readJsonFile { file in
if file == nil {
print("File does not exist!")
print(FileManager.default.currentDirectoryPath)
exit(EXIT_SUCCESS)
}
let dispatchGroup = DispatchGroup()
for servers in (file?.monitors)! {
dispatchGroup.enter()
let urlString = servers.url
print("1")
Services.shared.checkConnection(url: urlString, id: servers.component_id) { conresult in
print("2")
if conresult == .down {
print("\(urlString) is DOWN!")
} else {
print("\(urlString) is UP!")
}
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
}
dispatchMain()
它应该遍历每个URL并打印该URL是向上还是向下,但是输出如下:
1
1
2
https://esg3g2sdg32.com is DOWN!
2
https://esg3g2sdg32.com is DOWN!
logout
最终会打印1次,然后再打印2次,而不是一次打印1次和2次。
更新: 添加了信号灯:
Services.shared.readJsonFile { file in
print(FileManager.default.currentDirectoryPath)
if file == nil {
print("File does not exist!")
//print(FileManager.default.currentDirectoryPath)
exit(EXIT_SUCCESS)
}
let semaphore = DispatchSemaphore(value: 1)
let dispatchQueue = DispatchQueue(label: "taskQueue")
let dispatchGroup = DispatchGroup()
for servers in (file?.monitors)! {
dispatchQueue.async {
dispatchGroup.enter()
semaphore.wait()
let urlString = servers.url
print("1")
Services.shared.checkConnection(url: urlString, id: servers.component_id) { conresult in
print("2")
if conresult == .down {
print("\(urlString) is DOWN!")
} else {
print("\(urlString) is UP!")
}
dispatchGroup.leave()
semaphore.signal()
}
}
}
dispatchGroup.notify(queue: .main) {
//exit(EXIT_SUCCESS)
}
}
dispatchMain()
现在输出如下:
1
2
https://google.com is UP!
1
2
https://esg3g2sdg32.com is DOWN!
2
https://esg3g2sdg32.com is DOWN!
Illegal instruction: 4
logout
首先打印1,2个URL,然后再打印1,2个和第二个URL,然后又只打印2个和第二个URL。