2016-11-26 29 views
2

我試圖用斯威夫特3.從雅虎獲得股票報價雖然對斯威夫特2一些體面的教程,沒有人似乎很好地轉化爲斯威夫特3.SWIFT 3的URLRequest session.dataTask不點火

的我現在的問題是,在下面的代碼中,session.dataTask從不被調用。 print語句永遠不會觸發,其中的代碼不起作用。

我已檢查請求變量看起來不錯,並且該網址已在雅虎開發人員網站上進行了測試。

所以我想我必須有dataTask的語法錯誤或有一個錯誤,所以是完全跳過。

有什麼想法?

urlString = "http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quotes where symbol IN ('APL')" 

     //let urlNSS : NSString = urlString as NSString 
     let urlStr : String = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! 
     let url : URL = URL(string: urlStr as String)! 
     let request = URLRequest(url: url) 
     let session = URLSession.shared 
     let config = URLSessionConfiguration.default 

     let task = session.dataTask(with: request, completionHandler: {(data, response, error) -> Void in 

      print("in the task") 

      .. 
      .. 
     )} 

task.resume() 

如果我檢查的任務,我看到下面的 enter image description here

+0

這是一個命令行程序嗎?然後你需要一個運行循環:http://stackoverflow.com/questions/25126471/cfrunloop-in-swift-command-line-program。 - 還是一個遊樂場?然後這應該有所幫助:http://stackoverflow.com/questions/24058336/how-do-i-run-asynchronous-callbacks-in-playground。 –

回答

3

您必須恢復您已經創建任務(task.resume())。默認情況下,任務處於暫停狀態。

我使用不同的Yahoo RSS Feed URL創建了Playground文件。 https://drive.google.com/file/d/0B5nqEBSJjCriWl9UTWcxSE42Yk0/view?usp=sharing

您在問題中的URL沒有提供任何數據。

<error xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:lang="en-US"> 
<description>No definition found for Table yahoo.finance.quotes</description> 
</error> 

代碼如下:

//: Playground - noun: a place where people can play 

import UIKit 
import Foundation 
import PlaygroundSupport 
PlaygroundPage.current.needsIndefiniteExecution = true 
var str = "Hello, playground" 

let yahooURLString = "https://feeds.finance.yahoo.com/rss/2.0/headline?s=yhoo&region=US&lang=en-US" 
let yahooRSSURL: URL = URL(string: yahooURLString)! 

var request = URLRequest(url: yahooRSSURL) 
request.httpMethod = "GET" 

let sessionConfig = URLSessionConfiguration.default 
let session = URLSession(configuration: sessionConfig) 
let task = session.dataTask(with: request) {data, response, err in 
    print("Entered the completionHandler") 
    print("Response JSON:\n\(String(data: data!, encoding: String.Encoding.utf8)!)") 
} 
task.resume() 

希望這有助於。


編輯:附加出現在playgorund的控制檯打印語句的屏幕截圖。 enter image description here

+0

感謝您的回覆。如果我在模擬器中運行這個函數,我不會得到任何錯誤,但是這兩個print語句都不會觸發。所以無論是我如何調用函數都有問題,任務不允許在代碼中間使用print語句,或者模擬器不喜歡這種類型的代碼? –

+0

如果我在task.resume()之後放置斷點並檢查任務,它在任何組件中都沒有值 –

+0

@MichaelMoulsdale您是否下載並檢查了操場文件。我附上了一個在調試控制檯中輸出的輸出屏幕截圖。此外澄清打印聲明在模擬器以及內部任務,斷點也工作! –