从终端的互联网获取数据

时间:2017-08-20 17:21:20

标签: swift concurrency grand-central-dispatch

当我使用Xcode playground玩代码时,以下代码可以正常工作。可以将其分派回主队列并打印in main queue.

但是当我插入以下代码并将代码构建为bash命令时。它不起作用。它打印出除in main queue.以外的所有行。

因此,我相信如果代码在代码运行DispatchQueue.main.async时被编译为bash命令,则会发生无法分派到主队列的事情。我该如何解决这个问题?

import Foundation
let defaultSession = URLSession(configuration: URLSessionConfiguration.default)
let url = URL(string: "https://api.pearson.com/v2/dictionaries/ldec/entries?headword=test&apikey=zAONRFmzZsfQ4H4F53kJbpOzq9CUJtnS")
if let url = url {
    print("start")
    defaultSession.dataTask(with: url, completionHandler: {data, response, error in
        print("other queue.")
        if let error = error {
            print(error)
            return
        } else if let httpResponse = response as? HTTPURLResponse, 200...299 ~= httpResponse.statusCode, let data = data {//, let result = data as? Dictionary<String, Any> {
            //print(result)
            print("going back to the main queue")
            DispatchQueue.main.async {
                print("in main queue.")
            }
        } else {
            print("something really wrong")
        }
    }).resume()
}
while true {}

1 个答案:

答案 0 :(得分:-2)

看看下面的代码。它将与游乐场和终端一起使用。

import Foundation

var isRunning: Bool = true
let defaultSession = URLSession(configuration: URLSessionConfiguration.default)
let url = URL(string: "http://www.google.com")!
print("start")
defaultSession.dataTask(with: url, completionHandler: {data, response, error in
    print("other queue.")
    if let error = error {
        print(error)
        return
    } else if let httpResponse = response as? HTTPURLResponse, 200...299 ~= httpResponse.statusCode, let data = data {
        print("before main queue - isMainThread=",Thread.current.isMainThread)
        DispatchQueue.main.async {
            print("executed in main queue - isMainThread=",Thread.current.isMainThread)
            // you may consider exiting while loop               
            isRunning = false
        }
    } else {
        print("something really wrong")
    }
}).resume()
while(isRunning) {
    RunLoop.current.run(mode: RunLoopMode.defaultRunLoopMode, before: Date())
    usleep(3)
}