2015-06-09 30 views
3

我試圖來執行我打電話來填充我UITableView一個異步請求後tableView.reloadData()電話。該表在15-20秒後顯示數據,除非我手動開始滾動,在這種情況下,它會立即加載。所以數據肯定存在,只是沒有正確加載。我能做些什麼來解決這個問題?斯威夫特:tableView.reloadData()方法太慢

var jsonLoaded:Bool = false { 
     didSet { 
      if jsonLoaded { 

       tableView.reloadData() 

      } 
     } 
    } 

override func viewDidLoad() { 
     super.viewDidLoad() 

let url = NSURL(string: "https://www.googleapis.com/youtube/v3/search?part=id&q=\(searchTerm)&maxResults=1&key=AIzaSyD7PxAoq0O5hUxx775l_E_mnowlU4cUfcI") 

      let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in 

       if error != nil { 

        println(error) 

       } else { 

        let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary 

        if let items = jsonResult["items"] as? NSArray { 
         for songs in items { 
          if let id = songs["id"] as? NSDictionary { 
           if let videoId = id["videoId"] as? String { 
let newURL = NSURL(string: "https://www.googleapis.com/youtube/v3/search?relatedToVideoId=\(videoId)&part=snippet&type=video&maxResults=6&key=AIzaSyD7PxAoq0O5hUxx775l_E_mnowlU4cUfcI") 

            let newTask = NSURLSession.sharedSession().dataTaskWithURL(newURL!, completionHandler: {data, response, error -> Void in 

             if error != nil { 

              println(error) 

             } else { 

              let newJsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary 
              if let info = newJsonResult["items"] as? NSArray { 
               for videos in info { 
                if let snippet = videos["snippet"] as? NSDictionary { 
                 if let title = snippet["title"] as? String { 
                  self.recommendedTitles.append(title) 
                  self.jsonLoaded = true 

                } 
               } 
              } 
             } 
            }) 
            newTask.resume() 
           } 
          } 
        } 
       jsonLoaded = false 
      } 
      } 
     } 
    }) 
} 
} 
+0

誰是你的表的數據源? – Icaro

+0

這一切都內的'類:SongViewController:UIViewController中,的UITableViewDelegate,UITableViewDataSource {}' – chicobermuda

回答

4

的問題是,你在後臺線程設置jsonLoaded。這意味着reloadData()也在後臺線程上調用。但你必須從來沒有談話在後臺線程的接口!你需要做什麼涉及共享數據(如jsonLoaded)或接口之前走出主線程。

+1

哉! dispatch_async(dispatch_get_main_queue()){} – ggez44