【问题标题】:tableView is not showing data from JSON in swifttableView 没有快速显示来自 JSON 的数据
【发布时间】:2014-12-31 09:54:23
【问题描述】:

我正在解析来自HERE 的 JSON 数据。

为此,我使用了此代码。

DataManager.swift

import Foundation

let TopAppURL = "http://api.feedzilla.com/v1/categories.json"

class DataManager {

class func getTopAppsDataFromItunesWithSuccess(success: ((iTunesData: NSData!) -> Void)) {
    //1
    loadDataFromURL(NSURL(string: TopAppURL)!, completion:{(data, error) -> Void in
        //2
        if let urlData = data {
            //3
            success(iTunesData: urlData)
        }
    })
}

class func loadDataFromURL(url: NSURL, completion:(data: NSData?, error: NSError?) -> Void) {
var session = NSURLSession.sharedSession()

// Use NSURLSession to get data from an NSURL
let loadDataTask = session.dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
  if let responseError = error {
    completion(data: nil, error: responseError)
  } else if let httpResponse = response as? NSHTTPURLResponse {
    if httpResponse.statusCode != 200 {
      var statusError = NSError(domain:"com.raywenderlich", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
      completion(data: nil, error: statusError)
    } else {
      completion(data: data, error: nil)
    }
  }
})

loadDataTask.resume()
 }
}

ViewController.swift

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var i = 0
var detailid = [Int]()
var detailCat = [String]()
var tableData = ["1","2","3"]

@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()

DataManager.getTopAppsDataFromItunesWithSuccess { (iTunesData) -> Void in
    
    let json = JSON(data: iTunesData)
    
    if let array = json.arrayValue{

        for Dict in array{
            var id : Int = array[self.i]["category_id"].integerValue!
            var category : String = array[self.i]["english_category_name"].stringValue!
            self.detailid.append(id)
            self.detailCat.append(category)
            
            self.i++
            
        }
        println(self.detailid)
        println(self.detailCat)
    }
}


}

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


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
    cell.textLabel.text = self.detailCat[indexPath.row]
    return cell
    
   }

}

在控制台中我得到如下数据:

[1314, 13, 21, 22, 5, 588, 6, 17, 25, 1168, 11, 14, 2, 28, 15, 33, 591, 20, 29, 36, 3, 10, 16, 18, 8, 34, 4, 27, 30, 31, 26, 23, 12, 7, 590, 9, 19]
[Sports, Art, Blogs, Business, Celebrities, Columnists, Entertainment, Events, Fun Stuff, General, Health, Hobbies, Industry, Internet, IT, Jobs, Law, Life Style, Music, Oddly Enough, Politics, Products, Programming, Religion And Spirituality, Science, Shopping, Society, Sports, Technology, Top Blogs, Top News, Travel, Universities, USA, Video, Video Games, World News]

但它没有将其打印到tableView

我错过了什么?请帮帮我。

【问题讨论】:

    标签: ios json swift


    【解决方案1】:

    viewDidLoad 中的 for 循环 完成并获得数据后,您必须调用:

    tableView.reloadData()
    

    【讨论】:

      【解决方案2】:

      我还按照 Ray 的 iOS 应用教程进行操作,发现数据管理器无法在 for 循环之外传递数据。所以我用另一种方式来解析swiftyJSON。我花了一天的时间才弄清楚这一点。所以和你分享我的解决方案。我调用一个 url 来获取带有 json 中医院坐标列表的 json 数据,并在解析数据后将位置添加到 mapKit。

      让 locationURL = NSURL(string: "http: your url") var request = NSURLRequest(URL:locationURL!) var data = NSURLConnection.sendSynchronousRequest(request, returnedResponse: nil, error: nil)

          let json = JSON(data: data!)
      
          if let appArray = json.array {
      
                  for appDict in appArray {
                      var appName: String? = appDict["title"].string
                      var appLocation: String? = appDict["locationName"].string
                      var dLatitude: Double? = appDict["latitude"].doubleValue
                      var dLongitude: Double? = appDict["longitude"].doubleValue
                      var coordinate: CLLocationCoordinate2D? = CLLocationCoordinate2D(latitude: dLatitude!, longitude: dLongitude!)
      
      
                      hospital = HospitalModel(title: appName!,
                          locationName: appLocation!,
                          coordinate: CLLocationCoordinate2D(latitude: dLatitude!, longitude: dLongitude!))
      
                      hoslist.append(hospital)
      
                  }
                  mapView.addAnnotations(hoslist)
      
              }
      
          mapView.addAnnotations(hoslist)
      
          }
      

      【讨论】:

        猜你喜欢
        • 2022-11-13
        • 1970-01-01
        • 1970-01-01
        • 2022-01-08
        • 1970-01-01
        • 1970-01-01
        • 2017-03-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多