swift alamofire返回值为空 [英] swift alamofire return value is empty
问题描述
我有以下方法:
func getAlamoPlayers() ->[Player]{
//Get TeamID
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
var TeamId:String = prefs.stringForKey("TEAMID")!
//create parameters for POST
let parameters =
["IdTeam": TeamId]
var result: NSArray?
//Request
Alamofire.request(.POST, "XXXXXX.php", parameters: parameters)
.responseJSON { (request, response, json, error) -> Void in
result = (json as NSArray)
// Make models from Json data
for (var i = 0; i < result?.count; i++) {
let dic: NSDictionary = result![i] as NSDictionary
//Create a team object
var p:Player = Player()
//Assign the values of each key value pair to the team object
p.PlayerID = dic["IdPlayer"] as String
p.PlayerName = dic["name"] as String
p.PlayerFkToTeam = dic["teams_IdTeam"] as String
//Add the team to the player array
self.players.append(p)
}
}
return self.players
}
因此,当我在另一个类中调用此方法时,players数组为空!如何处理alamofire的异步请求?我认为该方法会在请求完成之前返回玩家对象,还是我错了?
So when i call this method in another class the players array is empty! How can I handle the asynchronous request of alamofire? I think the method returns the player object before the request is finished, or am I wrong?
谢谢!
推荐答案
这是一个与您基本相同的问题。
Here is a question that asks basically the same thing you are.
所以基本上发生的是您的发帖请求在后台队列中被调用。因此,将其视为致电您的帖子,然后继续进行下一行。因此,由于它位于后台线程中,因此直到函数返回后才设置变量。
So basically what is happening is that your post request is being called in a background queue. So think of it as calling your post then continuing on to the next line. So since it is in a background thread it doesn't set the variable till after your function returns.
您可以使用完成处理程序,如链接I中详细说明的那样提供。另一个解决方案是使用NSNotificationCenter。设置观察者,然后在POST请求中发布通知。
You could use a completion handler as explained in detail in the link I provided. Another solution would be to use NSNotificationCenter. Set up an observer and then post a notification inside your POST request.
因此,例如:
首先在类的顶部声明您的通知名称,您将在其中使用帖子响应功能。以便其他班级可以访问它
So for example: First declare your notification name at the top of the class where you will have your post response function as so. So that other classes can access it
让YOUR_NOTIFICATION_NAME = NOTIFICATION NAME
班级YOUR_CLASS {
然后在类内部编写您要在POST完成后执行的代码。
then inside the class write the code you want to execute once the POST is done.
func YOUR_FUNCTION {
...
}
然后在执行POST请求之前要添加
Then before you execute your POST request you want to add an observer.
NSNotificationCenter.defaultCenter()。addObserver(自身,选择器: YOUR_FUNCTION,名称:YOUR_NOTIFICATION_NAME,对象:nil)
然后在POST请求中发布通知。
Then post your notification inside your POST request.
Alamofire.request(.POST, "XXXXXX.php", parameters: parameters)
.responseJSON { (request, response, json, error) -> Void in
...<your code>...
self.players.append(p)
NSNotificationCenter.defaultCenter().postNotificationName(YOUR_NOTIFICATION_NAME, object: self)
}
这篇关于swift alamofire返回值为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!