本文介绍了得到变量的值超出关闭swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个闭包叫任务,它是一个后请求,我有一个全局变量名为values,我试图设置值值是从数据库中检索回存储在变量称为数组。不要担心tableview.reloadData部分,这已经完成了。
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();
}
}
}
value in viewdidload
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)")
}
这篇关于得到变量的值超出关闭swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!