get the value of variable out of closure swift

Percy Teng

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()
xmhafiz

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)")
    }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Get value from closure and add to numberOfRowsInSection swift

From Dev

NSURLConnection sendAsynchronousRequest can't get variable out of closure

From Java

Store a closure as a variable in Swift

From Dev

Swift variable declaration with closure

From Dev

How can I get initial closure variable in Swift?

From Dev

Getting data out of a closure in swift

From Dev

How to get variables out of closure?

From Dev

Get the value of a variable out of <iframe> or <object>

From Dev

swift closure stored and access as a variable

From Dev

Swift 2.0 - variable copied in closure?

From Dev

Swift value disappeared inside a closure

From Dev

Set a value within a closure swift

From Dev

Variable's value of JS Closure

From Dev

How to get copy of variable for closure?

From Dev

Can swift exit out of the root closure?

From Dev

Can swift exit out of the root closure?

From Dev

How do I move a variable out of a closure?

From Dev

Get variable name from value in Swift

From Dev

Moving value out of closure because of threading

From Dev

Closure default initializer missing - swift closure variable declaration?

From Dev

swift variable scope in closure wrt CLGeocoder()

From Dev

How to declare a local variable that is a closure in swift

From Dev

Swift: Closure as a init argument in a class variable

From Dev

swift variable scope in closure wrt CLGeocoder()

From Dev

Swift - return variable from within closure

From Dev

Modify Global Variable Inside Closure (Swift 4)

From Dev

How to return value from a Closure in Swift?

From Dev

Retrieve String value from function with closure in Swift

From Dev

Capturing a value from closure in Swift with Parse

Related Related

HotTag

Archive