I am making a command line tool in Xcode. The tool reads urls from a JSON file and then it should loop through each URL and check to see if the urls return a 200 HTTP code. I would like each url to run and then when each url check is done, move to the next one. My current code is as follows:
Services.shared.readJsonFile { file in
if file == nil {
print("File does not exist!")
print(FileManager.default.currentDirectoryPath)
exit(EXIT_SUCCESS)
}
let dispatchGroup = DispatchGroup()
let dispatchQueue = DispatchQueue(label: "taskQueue")
let dispatchSemaphore = DispatchSemaphore(value: 0)
dispatchQueue.async {
for servers in (file?.monitors)! {
let urlString = servers.url
print("1")
dispatchGroup.enter()
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!")
}
dispatchSemaphore.signal()
dispatchGroup.leave()
}
dispatchSemaphore.wait()
}
}
dispatchGroup.notify(queue: dispatchQueue) {
exit(EXIT_SUCCESS)
}
}
dispatchMain()
I added a print 1 and print 2 to see the order in which it is being printed and for some reason the output is as follows:
1
2
https://google.com is UP!
1
2
https://esg3g2sdg32.com is DOWN!
2
https://esg3g2sdg32.com is DOWN!
Illegal instruction: 4
I only have two urls in the file but it always runs the second url twice and it looks like it prints out "2" twice at the end without going back to "1".
UPDATE: Removed semaphores as follows:
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()
and now my output is this:
1
1
2
https://esg3g2sdg32.com is DOWN!
2
https://esg3g2sdg32.com is DOWN!
logout