2016-03-01 119 views
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 
+0

是否缺少一些代碼? 'jsonDict'似乎沒有被定義在任何地方,而'else'似乎沒有與'if'配對。 '// 4'是可疑的失蹤。 – Michael

+0

不,這是完整的代碼。@ Michael –

+0

你如何定義它。 @Michael –

回答

1

此刻你已經得到了一些沒有意義的代碼。例如else沒有相應的if。我不知道你想要用你的代碼做什麼,但它應該看起來像下面的內容。請注意,這也是錯誤的。你需要回到你得到原始代碼的地方,因爲你現在的代碼永遠不會工作。

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 jsonDict = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary { 
       // Success block... 
       //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]) 
       }) 
      } 
     } catch { 
      print(error) 
     } 

    }) 


    //6: DONT FORGET to LAUNCH the NSURLSessionDataTask!!!!!! 
    task.resume() 
} 
+0

嘿,非常感謝你,終於有用了。 @邁克爾 –