简体   繁体   中英

get the value of variable out of closure swift

So I have a closure called task which is a post request and I have a global variable called values and I'm trying to set the value of "values" to be the data that I retrieved back from database stored in a variable called "array". Don't worry about the tableview.reloadData part, that's already done. i just wanna know how to get the value out of closure.

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()
    print ("values=\(values)")

}
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

        dispatch_async(dispatch_get_main_queue()) { [unowned self] in
            self.values = array
            print ("error=\(self.values)")
            self.tableView?.reloadData();
        }
    }
    task.resume()

use completion for any asynchronous task in closure

func get(completion:(value: NSArray) -> Void){

    // request part
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in
        // your serialization code

        dispatch_async(dispatch_get_main_queue()) { [unowned self] in
            self.values = array

            // return value to completion
            completion(value: array)

            print ("error=\(self.values)")
            self.tableView?.reloadData();
        }
    }
} 

change the way you get the value in viewdidload

   get{(value) in
       // finish NSURLSession task and everything should be done in this closure
        self.values = value
        print ("values=\(self.values)")
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM