Swift命令行异步未等待

时间:2018-07-23 14:12:42

标签: swift macos

我正在用Xcode制作命令行工具。该工具从JSON文件读取网址,然后应循环访问每个网址,并检查该网址是否返回200 HTTP代码。我希望运行每个URL,然后在完成每个URL检查后,移至下一个。我当前的代码如下:

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()

我添加了打印件1和打印件2,以查看打印顺序,由于某种原因,输出如下:

1
2
https://google.com is UP!
1
2
https://esg3g2sdg32.com is DOWN!
2
https://esg3g2sdg32.com is DOWN!
Illegal instruction: 4

我在文件中只有两个url,但它总是运行第二个url两次,看起来它在末尾打印两次“ 2”而不返回“ 1”。

更新: 删除了以下信号灯:

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()

现在我的输出是这样:

1
1
2
https://esg3g2sdg32.com is DOWN!
2
https://esg3g2sdg32.com is DOWN!
logout

0 个答案:

没有答案