Reputation: 95
I'm trying to get the Price
and Change
data from Yahoo finance API in JSON format. Apple Stock API
However there are some issues when unwrapping the data. The program shows issue when executing for jsonObjectString in resultArray!
. I suspect it found no data, because the error during debug was 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()
}
Upvotes: 1
Views: 1242
Reputation: 1379
resultJSON is dictionary, which is why it is returning nil when you cast it to NSArray
.
if you want to get the value for price and change, try this instead.
let resultDict = resultJSON as? NSDictionary
let queryDict = resultDict["query"]
let resultsDict = queryDict["results"]
let rowDict = resultsDict["row"]
let price = rowDict["price"] as! String
let change = rowDict["change"] as! String
Upvotes: 1