0
我一直在从雅虎财务使用jSon获取股票数据的应用程序,但我在错误代码中遇到问题。它在else语句中表示未解析的标识符jsonDict和预期的表达式错误。Json雅虎Api错误
这是代码。
import Foundation
let kNotificationStocksUpdated = "stocksUpdated"
class StockManagerSingleton {
//Singleton Init
class var sharedInstance : StockManagerSingleton {
struct Static {
static let instance : StockManagerSingleton = StockManagerSingleton()
}
return Static.instance
}
/*!
* @discussion Function that given an array of symbols, get their stock prizes from yahoo and send them inside a NSNotification UserInfo
* @param stocks An Array of tuples with the symbols in position 0 of each tuple
*/
func updateListOfSymbols(stocks:Array<(String,Double)>) ->() {
//1: YAHOO Finance API: Request for a list of symbols example:
//http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quotes where symbol IN ("AAPL","GOOG","FB")&format=json&env=http://datatables.org/alltables.env
//2: Build the URL as above with our array of symbols
var stringQuotes = "(";
for quoteTuple in stocks {
stringQuotes = stringQuotes+"\""+quoteTuple.0+"\","
}
stringQuotes = stringQuotes.substringToIndex(stringQuotes.endIndex.predecessor())
stringQuotes = stringQuotes + ")"
let urlString:String = ("http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quotes where symbol IN "+stringQuotes+"&format=json&env=http://datatables.org/alltables.env").stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let url : NSURL = NSURL(string: urlString)!
let request: NSURLRequest = NSURLRequest(URL:url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
//3: Completion block/Clousure for the NSURLSessionDataTask
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
do {
if let _ = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary {
// Success block...
}
} catch {
print(error)
}
else {
//5: Extract the Quotes and Values and send them inside a NSNotification
var quotes:NSArray = ((jsonDict.objectForKey("query") as NSDictionary).objectForKey("results") as NSDictionary).objectForKey("quote") as NSArray
dispatch_async(dispatch_get_main_queue(), {
NSNotificationCenter.defaultCenter().postNotificationName(kNotificationStocksUpdated, object: nil, userInfo: [kNotificationStocksUpdated:quotes])
})
}
})
//6: DONT FORGET to LAUNCH the NSURLSessionDataTask!!!!!!
task.resume()
}
}
有问题的代码行是。
var quotes:NSArray = ((jsonDict.objectForKey("query") as NSDictionary).objectForKey("results") as NSDictionary).objectForKey("quote") as NSArray
是否缺少一些代码? 'jsonDict'似乎没有被定义在任何地方,而'else'似乎没有与'if'配对。 '// 4'是可疑的失踪。 – Michael
不,这是完整的代码。@ Michael –
你如何定义它。 @Michael –