我无法在第二个UIViewController中显示json数据

时间:2016-05-23 15:40:03

标签: ios json swift nsurlsession nsurl

我的第一个ViewController中有以下两个函数。他们加载了超过300行的UITableView。我在ViewDidLoad中调用loadRemoteData函数。在第一个ViewController中,一切正常。

 // MARK: - parseJSON
func parseJSON(data: NSData) {
    do {
        let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)

        if let rootDictionary = json as? [NSObject: AnyObject], rootResults = rootDictionary["results"] as? [[NSObject: AnyObject]] {
            for childResults in rootResults {
                if let firstName = childResults["first_name"] as? String,
                    let lastName = childResults["last_name"] as? String,
                    let bioguideId = childResults["bioguide_id"] as? String,
                    let state = childResults["state"] as? String,
                    let stateName = childResults["state_name"] as? String,
                    let title = childResults["title"] as? String,
                    let party = childResults["party"] as? String {
                    let eachLegislator = Legislator(firstName: firstName, lastName: lastName, bioguideId: bioguideId, state: state, stateName: stateName, title: title, party: party)
                    legislators.append(eachLegislator)
                }
            }
        }
    } catch {
        print(error)
    }
}

// MARK: - Remote Data configuration
func loadRemoteData() {
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config)
    let url = "https://somedomain.com/legislators?order=state_name__asc,last_name__asc&fields=first_name,last_name,bioguide_id"
    if let url = NSURL(string: url) {
        let task = session.dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
            if let error = error {
                print("Data Task failed with error: \(error)")
                return
            }
            if let http = response as? NSHTTPURLResponse, data = data {
                if http.statusCode == 200 {
                    dispatch_async(dispatch_get_main_queue()) {
                        self.parseJSON(data)
                        self.tableView.reloadData()
                    }
                }
            }
        })
        task.resume()
    }
}

在第二个ViewController中,我想显示有关在被点击的单元格中列出的个人的更多信息,因为我使用了不同的URL,例如https://somedomain.com/legislators?bioguide_id=\"\(bioguideId)\",这为我提供了更多细节。 (从JSON字典请​​求的数据不同)

我在第二个ViewController中使用的代码如上所示,唯一的区别是URL。我可以打印来自前一个ViewController的url,它会显示在控制台日志中,但不会显示json数据。

我将不胜感激任何帮助。 感谢

下面是我的第二个ViewController的代码:

import UIKit

class DetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var bioguideId: String?
var currentLegislator: Legislator? = nil
var currentLegislatorUrl: String?
let reuseIdentifier = "Cell"

@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var tableView: UITableView!

// MARK: - parseJSON
private func parseJSON(data: NSData) {
    do {
        let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
        if let rootDictionary = json as? [NSObject: AnyObject],
            rootResults = rootDictionary["results"] as? [[NSObject: AnyObject]] {
            for childResults in rootResults {
                if let firstName = childResults["first_name"] as? String,
                    let lastName = childResults["last_name"] as? String,
                    let bioguideId = childResults["bioguide_id"] as? String,
                    let state = childResults["state"] as? String,
                    let stateName = childResults["state_name"] as? String,
                    let title = childResults["title"] as? String,
                    let party = childResults["party"] as? String {
                    currentLegislator = Legislator(firstName: firstName, lastName: lastName, bioguideId: bioguideId, state: state, stateName: stateName, title: title, party: party)
                }
            }
        }
    } catch {
        print(error)
    }
}

// MARK: - Remote Data configuration
func loadRemoteData(url: String) {
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config)
    let url = currentLegislatorUrl
    if let url = NSURL(string: url!) {
        let task = session.dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
            if let error = error {
                print("Data Task failed with error: \(error)")
                return
            }
            print("Success")
            if let http = response as? NSHTTPURLResponse, data = data {
                if http.statusCode == 200 {
                    dispatch_async(dispatch_get_main_queue()) {
                        self.parseJSON(data)
                        self.tableView.reloadData()
                    }
                }
            }
        })
        task.resume()
    }
}

func loadImage(urlString:String) {
    let imgURL: NSURL = NSURL(string: urlString)!
    let request: NSURLRequest = NSURLRequest(URL: imgURL)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(request){
        (data, response, error) -> Void in
        if (error == nil && data != nil) {
            func display_image() {
                self.imageView.image = UIImage(data: data!)
            }
            dispatch_async(dispatch_get_main_queue(), display_image)
        }
    }
    task.resume()
}

override func viewDidLoad() {
    super.viewDidLoad()
    print(currentLegislatorUrl!)
    loadRemoteData(currentLegislatorUrl!)
    loadImage("https://theunitedstates.io/images/congress/225x275/\(bioguideId!).jpg")

    self.title = bioguideId
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath)
    cell.textLabel!.text = currentLegislator?.firstName
    return cell
}

}

1 个答案:

答案 0 :(得分:0)

感谢Adam H.他的评论使我重新评估了我正在使用的URL并添加了其他运算符,现在数据显示在我的第二个ViewController中。