2015-04-05 43 views
0

我必須把數據放在tableview中,但即使很難從JSON獲取信息,我也無法將數據傳遞給postTitle變量。這是爲什麼?這裏是我的代碼:如何在Swift中將數據從NSArray傳輸到字符串?

import UIKit 

class ViewController: UIViewController, UITableViewDelegate,  UITableViewDataSource { 

var postTitle = [AnyObject]() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    var baseURL = "https://hacker-news.firebaseio.com/v0/topstories.json" 

    //  https://hacker-news.firebaseio.com/v0/item/9324191.json 

    if let url = NSURL(string: baseURL) { 
     var taskURL = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in 

      if error != nil { 
       println("Error: \(error.localizedDescription)") 
      } else { 
       var jsonError: NSError? 
       if let topStories = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? NSArray { 

         self.postTitle.append(topStories) 

       } 


      } 

     }) 


     taskURL.resume() 

    } 


} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    println(postTitle.count) 
    return postTitle.count 
} 



func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    var cell = UITableViewCell() 

    println(self.postTitle) 
    // cell.textLabel?.text = postTitle[indexPath.row] 
    return cell 
} 




override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 


} 
+0

你看到什麼錯誤? – 2015-04-05 21:01:55

+0

你知道'dataTaskWithURL()'**異步工作**嗎? - 請參閱http://stackoverflow.com/questions/28782932/tableview-is-not-updating-until-i-tap-another-tab-and-get-back-swift,或搜索「從異步中獲取值功能」。 – 2015-04-05 21:11:23

回答

0

所以來自Reddit的其他人幫助我。我錯過了幾件事。首先是數據類型Int,它需要傳遞給實例變量,其次是UITableView:這裏是工作解決方案。希望這會幫助某人。

進口的UIKit

類的ViewController:UITableViewController中,的UITableViewDelegate,UITableViewDataSource {

var postTitles = [Int]() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    var baseURL = "https://hacker-news.firebaseio.com/v0/topstories.json" 


    if let url = NSURL(string: baseURL) { 
     var taskURL = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in 

      if error != nil { 
       println("Error: \(error.localizedDescription)") 
      } else { 
       var jsonError: NSError? 
       if let topStories = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? [Int] { 
         self.postTitles = Array(topStories[0...9]) 

         // Reload the table with our new results! 
         self.tableView.reloadData() 
       } 
      } 

     }) 

     taskURL.resume() 

    } 
} 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return postTitles.count 
} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell 


    let postTitle = String(self.postTitles[indexPath.row]) 

    cell.textLabel?.text = postTitle 

    return cell 
    } 
} 
1

topStoriesNSArray,但你是追加到postTitle陣列(它的類型是[AnyObject]的)。 Array.append將單個項目添加到數組中。因此,您將在postTitle陣列中添加一個條目(NSArray)。

我猜你想要的是將topStories的內容添加到postTitle?在這種情況下你要使用的extend而非append方法:

self.postTitle.extend(topStories) 
+0

或者使用'+ ='語法:'self.postTitle + = topStories' – 2015-04-05 22:14:45

+0

問題是我有這個函數返回我的0,即使把@Airspeed Velocity建議。 'FUNC的tableView(的tableView:UITableView的,numberOfRowsInSection段中:int) - >詮釋{ 的println(postTitle.count) 回報postTitle.count } ' – 2015-04-06 08:42:08

0

既然你顯然重裝所有的冠軍對每個請求,你可以很容易地做到這一點:self.titles = topStories

我剛建這樣的測試應用程序,它工作得很好。

PS:self.postTitle.append無論如何都會產生錯誤的結果,因爲它也會在您的數組中添加標題。你可能應該使用的方法是self.postTitle.join,因爲它使用交集。

+0

它沒有工作。沒有任何內容存儲在postTitle變量中,但是如果在JSONSerialization之後println(self.postTitles),它會將值存儲在該變量中。我不明白。 – 2015-04-06 10:57:27

+0

這裏是[我的工作代碼的要點](https://gist.github.com/Jan0707/b401441ee65c7a26f485) – Jan 2015-04-06 12:30:43

+0

如果我爲你編碼的話,請如此善良,並將我的答案標記爲已接受的答案。 – Jan 2015-04-06 18:44:26

相關問題