2017-09-20 54 views
0

我想弄清最簡單的方式來在Swift 4中發出HTTP請求。我已從URLSession programming guide複製此代碼,並添加了幾個打印語句。我無法弄清楚爲什麼.dataTask沒有執行。從文檔不工作的Swift 4 URLSession示例代碼

print("Testing URLSession") 
let sessionWithoutADelegate = URLSession(configuration: URLSessionConfiguration.default) 
if let url = URL(string: "https://www.example.com/") { 
    print("Encoded url \(url)") 
    (sessionWithoutADelegate.dataTask(with: url) { (data, response, error) in 
     print("Executing dataTask") 
     if let error = error { 
      print("Error: \(error)") 
     } else if let response = response, 
      let data = data, 
      let string = String(data: data, encoding: .utf8) { 
      print("Response: \(response)") 
      print("DATA:\n\(string)\nEND DATA\n") 
     } 
    }).resume() 
} 

的最終目的是從一個REST API檢索數據,但我甚至不能做一個簡單的GET請求正常工作......

+1

這是在iOS或macOS應用程序或命令行應用程序中?或在遊樂場? –

+0

這是在命令行應用程序中。我在一個操場上試了一下,但它似乎沒有正常工作,因爲它停止在右側顯示值,即使是打印報表等。 – mooglinux

+1

...結束大括號後是否有任何代碼,或者程序是否結束? 'URLSessionTask'異步運行,所以如果程序在結束之前結束,你永遠不會看到它的結果。 – NobodyNada

回答

2

我終於想通了,如何使它工作中使用CFRunLoop

let runLoop = CFRunLoopGetCurrent() 
let task = session.dataTask(with: request) { (data, response, error) in 
    print("Retrieved data") 
    CFRunLoopStop(runLoop) 
} 
task.resume() 
CFRunLoopRun() 
print("done")