返回DetailTableView中的数据(swift)

时间:2016-02-11 18:54:58

标签: ios swift

在我的应用程序中,我有两个表视图。第一个表视图具有一定数量的单元格。这些单元格将始终相同并且永远不会更改上面的表格视图将始终具有4个单元格,而且永远不会更多。在我的服务器上,我有我的API,其中包含每个单元格的路径。

例如:

GET - myAPI / Air

GET - myAPI / history

GET - myAPI / train

GET - myAPI / taxi

每条路线发回不同的数据

  

mainTablewView:

import UIKit
 enum NeededAPI {
case Air
case History
case Train
case Taxi
}
class mainTableViewController : UITableViewController {
struct WeatherSummary {
    var id: String
}

var testArray = NSArray()
var manuArray = NSArray()

// Array of sector within our company
var selectSector: [String] = ["Air", "History","Train","Taxi"]

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.rowHeight = 80.0
}

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

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    return 1
}

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


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("sectorList", forIndexPath: indexPath) 
    // Configure the cell...

    if selectSector.count > 0 {

        cell.textLabel?.text = selectSector[indexPath.row]
    }

    return cell
}


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if (segue.identifier == "AirSegue"){
        if let destination = segue.destinationViewController as? AirTableViewController {
            let indexPath:NSIndexPath = self.tableView.indexPathForSelectedRow!

            if let row:Int = indexPath.row {

            destination.apiThatNeedsToBeCalled = .Air

            }


        }
    }
    if (segue.identifier == "HistorySegue"){
        if let destination = segue.destinationViewController as? HistoryTableViewController {
            let indexPath:NSIndexPath = self.tableView.indexPathForSelectedRow!

            if let row:Int = indexPath.row {

                destination.apiThatNeedsToBeCalled = .History

            }


        }
    }
    if (segue.identifier == "TrainSgue"){
        if let destination = segue.destinationViewController as? TrainTableViewController {
            let indexPath:NSIndexPath = self.tableView.indexPathForSelectedRow!

            if let row:Int = indexPath.row {

                destination.apiThatNeedsToBeCalled = .Train

            }


        }
    }
    if (segue.identifier == "TaxiSegue"){
        if let destination = segue.destinationViewController as? TaxiTableViewController {
            let indexPath:NSIndexPath = self.tableView.indexPathForSelectedRow!

            if let row:Int = indexPath.row {

                destination.apiThatNeedsToBeCalled = .Taxi

            }


        }
    }




}

}
  

和发布

import Foundation
class Post : CustomStringConvertible {
var userId:Int
var title: String

init(userid:Int , title:String){
    self.userId = userid
    self.title = title
}

var description : String { return String(userId) }

}

当用户选择单元格时,您为apiThatNeedsToBeCalled设置了正确的值。一旦你这样做,didSet中的代码将被执行,它应该调用调用适当API的函数。

  

到其他tableView:

import UIKit

class AirTableViewController: UITableViewController {

var postCollection = [Post]()
        var apiThatNeedsToBeCalled:NeededAPI = .Air {
        didSet {
            //check which API is set and call the function which will call the needed API
            AirLine()

        }
    }

override func viewDidLoad() {
    super.viewDidLoad()




}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
var apiThatNeedsToBeCalled:NeededAPI = .Air {
    didSet {
        //check which API is set and call the function which will call the needed API
        AirLine()

    }
}

func AirLine(){

    let url = NSURL(string: "http://jsonplaceholder.typicode.com/posts")
    NSURLSession.sharedSession().dataTaskWithURL(url!){[unowned self] (data , respnse , error) in
        if error != nil{

            print(error!)
        }else{

            do{

                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [[String:AnyObject]]

                UIApplication.sharedApplication().networkActivityIndicatorVisible = false

                var newPost = Iduser(id: 0)

                for posts in json {

                    let postObj = Post(userid:posts["userId"] as! Int,title: posts["title"] as! String)

                    self.postCollection.append(postObj)
                }

                dispatch_async(dispatch_get_main_queue()){
                    self.tableView.reloadData()
                }
            }catch let error as NSError{

                UIApplication.sharedApplication().networkActivityIndicatorVisible = true
                print(error.localizedDescription)
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON:\(jsonStr)")

                dispatch_async(dispatch_get_main_queue()) {

                    let alert = UIAlertController(title: "Alert", message: "Oops! Wrong Details, Try Again", preferredStyle: UIAlertControllerStyle.Alert)
                    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
                    self.presentViewController(alert, animated: true, completion: nil)


                }

            }

        }

    }
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return self.postCollection.count ?? 0
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("AirCell", forIndexPath: indexPath)

    // Configure the cell...

    // cell.textLabel?.text = "test"

    let weatherSummary = postCollection[indexPath.row]


        cell.textLabel?.text = String(weatherSummary.userId)

        cell.detailTextLabel?.text = weatherSummary.title




    return cell
}

}

mainTableView和Air单元格确定但是当选择其他返回相同的信息Air cell?

1 个答案:

答案 0 :(得分:0)

也许我只是错过了它,但我可以看到你创建的NSURLSession看起来很好,但是一旦你创建了它,我就看不到你在那里调用.resume()的位置了。如果你不打电话给.resume(),它根本就不会执行那个URLSession。查看讨论here