简体   繁体   中英

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.

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.

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.

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


            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM