Swift PHP post请求从任务设置全局变量

时间:2016-06-29 02:16:18

标签: ios swift closures global-variables

我使用post请求成功从数据库中检索数据。 (我不想使用获取请求因为我想向php发送验证。)不要担心php部分,它应该没问题。

import UIKit

class mainPage: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var toolBar: UIToolbar!
    var values:NSArray = []

    @IBOutlet weak var Open: UIBarButtonItem!
    override func viewDidLoad() {
        super.viewDidLoad()


        Open.target = self.revealViewController()
        Open.action = #selector(SWRevealViewController.revealToggle(_:))
        self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        get()

    }
    func get(){
        let request = NSMutableURLRequest(URL: NSURL(string: "http://www.percyteng.com/orbit/getAllpostsTest.php")!)
        request.HTTPMethod = "POST"
        let postString = "user=\("ios")"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in
            if error != nil {

                print("error=\(error)")
                return
            }

            print("response = \(response)")

            let array = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
            self.values = array
        }
        task.resume()
    dispatch_async(dispatch_get_main_queue()) { tableView.reloadData()}
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if values.count > 20{
            return 20
        }
        else{
            return values.count
        }
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as!postCell

        let maindata = values[values.count-1-indexPath.row]
        if maindata["category"] as? String == "Services"{
            cell.postImg.image = UIImage(named: "tile_services")
        }
        else if maindata["category"] as? String == "exchange"{
            cell.postImg.image = UIImage(named: "tile_exchange")
        }
        else if maindata["category"] as? String == "Tutors"{
            cell.postImg.image = UIImage(named: "tile_tutoring")
        }
        else if maindata["category"] as? String == "Sports"{
            cell.postImg.image = UIImage(named: "tile_sports")
        }
        else if maindata["category"] as? String == "Sublet"{
            cell.postImg.image = UIImage(named: "tile_sublet")
        }
        else if maindata["category"] as? String == "Events"{
            cell.postImg.image = UIImage(named: "tile_events")
        }
        else{
            cell.postImg.image = UIImage(named: "tile_carpool")
        }


        if maindata["category"] as? String == "Services" || maindata["category"] as? String == "Tutors" || maindata["category"] as? String == "Events"{
            cell.title.text = maindata["title"] as? String
        }
        else if maindata["category"] as? String == "Sublet" || maindata["category"] as? String == "Rideshare"{
            cell.title.text = maindata["location"] as? String
        }
        else{
            cell.title.text = maindata["item"] as? String
        }


        if maindata["category"] as? String == "Sublet" || maindata["category"] as? String == "Rideshare"{
            cell.location.text = ""
        }
        else{
            cell.location.text = maindata["location"] as? String
        }
        cell.category.text = maindata["category"] as? String
        cell.price.text = maindata["price"] as? String
        return cell
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    }
}

所以我有一个名为values的全局变量,它是一个NSArray,我想将这个数组的值设置为我从数据库中检索的数组。但是,在函数get()中,post请求充当另一个线程,我必须编写self.values = array,它不会改变我的全局变量的值。

我需要该值来在主数组中组织我的tableview。

基本上,我的问题是如何从闭包中获取值并将其设置为全局变量。

谢谢!如果你们不理解我所说的话,请告诉我。

2 个答案:

答案 0 :(得分:1)

您需要func get()中的完成处理程序才能执行dataTaskWithRequest Async来电func get(finished: (isDone: Bool) -> ()){ //your code data, response, error in if error != nil { finished(isDone: false) print("error=\(error)") return } print("response = \(response)") let array = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray self.values = array } } task.resume() finished(isDone: true) } 。试试这个:

viewDidLoad

然后在 override func viewDidLoad() { super.viewDidLoad() get { success in if success{ //reload your tableview here } }

{{1}}

答案 1 :(得分:0)

闭包隐式保留self,因此您实际上正在修改该属性。但是,您需要在使用reloadCellsAtIndexPathinsertCellsAtIndexPathreloadData在闭包内检索数据后刷新tableView。后者是最简单的方法,但完全取代了表的当前状态。

此外,您正在关闭中导致保留周期。您应该将自己作为weakunowned属性传递给ARC以使其完成工作。有关该问题的更多信息:http://krakendev.io/blog/weak-and-unowned-references-in-swift

示例:

func get(){
    let request = NSMutableURLRequest(URL: NSURL(string: "http://www.percyteng.com/orbit/getAllpostsTest.php")!)
    request.HTTPMethod = "POST"
    let postString = "user=\("ios")"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in
        if error != nil {

            print("error=\(error)")
            return
        }

        print("response = \(response)")

        let array = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
        self.values = array
        dispatch_async(dispatch_get_main_queue()) { [unowned self] in
            self.tableView?.reloadData();
        }
    }
    task.resume()
}