2016-07-22 31 views
0

當我嘗試運行這個項目時,我迎來了一個「使用未解析的標識符錯誤」。這裏是代碼我上線的誤差與我不斷收到一個使用未解決的標識符錯誤swift

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

        }) 
        } 
       } 

      } 
     }) 

可有人請幫助。謝謝。

+0

哪一行,你得到的錯誤? – WMios

+0

是的,它發生在哪條線上? –

+0

@WMios我剛剛更新了代碼,以顯示錯誤的位置 –

回答

0

您的問題可能是catch塊中的這一行代碼。

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

在上述聲明jsonDict超出範圍。您在do塊中聲明瞭jsonDict,但正試圖在catch塊中使用它。

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 


      } 
相關問題