首页 文章

我一直在使用未解析的标识符错误swift

提问于
浏览
0

当我尝试运行这个项目时,我遇到了“使用未解析的标识符错误” . 这是我得到错误的代码

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])

                    })
                    }
                }

            }
        })

有人可以帮忙吗谢谢 .

3 回答

  • 0

    这个代码的蜘蛛网正是SwiftyJSON库存在的原因 . 我推荐它很高,它可以使用cocoapods导入到你的项目中 .

    使用这个库得到的代码将是

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

    这更具可读性,并且当您实现更多API时,速度更快 .

  • 0

    尝试以下: - (假设JSON具有根节点结构)

    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
    
    
                }
    
  • 0

    问题可能是 catch 块中的这行代码 .

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

    在上面的语句中 jsonDict 超出了范围 . 您在 do 块中声明了jsonDict,但正在尝试在 catch 块中使用它 .

相关问题