我必須把數據放在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.
}
}
你看到什麼錯誤? – 2015-04-05 21:01:55
你知道'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