Paul Butler
Paul Butler

Reputation: 17

I keep getting a use unresolved identifier error swift

When I try to run this project I am greeted with a "Use of unresolved identifier error." Here is the code I get the error on the line with

var jsonDict =  try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
 as! NSDictionary
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in

            if((error) != nil) {
                print(error!.localizedDescription)
            } else {

                let err: NSError?
                do {
                var jsonDict =  try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
                } catch {
                if(err != nil) {
                    print("JSON Error \(err!.localizedDescription)")
                }

                else {
                    //5: Extract the Quotes and Values and send them inside a NSNotification
                    let 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])

                    })
                    }
                }

            }
        })

can someone please help. Thank you.

Upvotes: 0

Views: 1331

Answers (3)

Sameer J
Sameer J

Reputation: 236

this cobweb of code is exactly why SwiftyJSON library exists. I recommend it highly, it can be imported into your project using cocoapods.

using this library the resultant code would be

jsonQuery["query"]["results"]["quote"]

which is more readable and as you implement more APIs, much faster.

Upvotes: 0

Meet
Meet

Reputation: 1206

Try Following:- (Assuming JSON has a root node structure)

let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: yourURL)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(urlRequest) {
            (data, response, error) -> Void in

            let httpResponse = response as! NSHTTPURLResponse
            let statusCode = httpResponse.statusCode

            if (statusCode == 200) {

                do{

                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)



                    if let queries = json["query"] as? [[String: AnyObject]] {
                            for query in queries {
                                if let quote = query["quote"] as? String {
                                        self.quoteArr.append(quote)
                                }

                            }//for loop
                            dispatch_async(dispatch_get_main_queue(),{
                               // your main queue code 
NSNotificationCenter.defaultCenter().postNotificationName(kNotificationStocksUpdated, object: nil, userInfo: [kNotificationStocksUpdated:quotes])
                            })//dispatch

                    }// if loop

                }
                catch
                {
                    print("Error with Json: \(error)")

                }

            }
            else
            {
                // No internet connection
                // Alert view controller
                // Alert action style default


            }

Upvotes: 0

user1766802
user1766802

Reputation:

You problem could be this line of code in the catch block.

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

In the above statement jsonDict is out of scope. You declared jsonDict in the do block but are trying to use it in the catch block.

Upvotes: 0

Related Questions