Luc Mollard
Luc Mollard

Reputation: 29

Json Yahoo Api Error

I have been working on an App that gets stock data using jSon from Yahoo Finance but I have a problem in the error code. It says unresolved identifier jsonDict and an expected expression error, in the else statement.

Here is the code.

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()
}
}

The problematic line of code is.

var quotes:NSArray = ((jsonDict.objectForKey("query") as NSDictionary).objectForKey("results") as NSDictionary).objectForKey("quote") as NSArray

Upvotes: 0

Views: 324

Answers (1)

Michael
Michael

Reputation: 9042

At the moment you've got bits of code that don't make sense. For example the else has no corresponding if. I don't know what you're wanting to do with your code, but it should look something along the lines of that below. Note that this will be wrong too. You need to go back to the source of where you got the original code from, as your current code will never work.

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()
}

Upvotes: 1

Related Questions