1
我正在嘗試以JSON格式從Yahoo finance API獲取Price
和Change
數據。 Apple Stock API用Swift展開雅虎API
但是,在解包數據時有一些問題。該程序在執行for jsonObjectString in resultArray!
時顯示問題。我懷疑它發現沒有數據,因爲調試過程中的錯誤是fatal error: unexpectedly found nil while unwrapping an Optional value
func GetPrice(){
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "https://query.yahooapis.com/v1/public/yql?q=select%20price%2C%20change%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes.csv%3Fs%3DA17U.SI%26f%3Dsl1d1t1c1ohgv%26e%3D.csv'%20and%20columns%3D'symbol%2Cprice%2Cdate%2Ctime%2Cchange%2Ccol1%2Chigh%2Clow%2Ccol2'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys")!)
request.HTTPMethod = "GET"
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let data = data{
do{
let resultJSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
let resultArray = resultJSON as? NSArray
for jsonObjectString in resultArray!{
let price = jsonObjectString["price"] as! String
let change = jsonObjectString["change"] as! String
self.priceList.append(PriceTable(stockCode: self.blueChipList[self.index].stockName, price: price, change: change))
}
dispatch_async(dispatch_get_main_queue(), {self.tableView.reloadData()})
}catch _{
print("Received not-well-formatted JSON")
}
}
if let response = response {
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}