swift alamofire的返回值是空的

时间:2015-03-31 20:21:22

标签: swift alamofire

您好我有以下方法:

    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
}

所以当我在另一个类中调用此方法时,player数组是空的!如何处理alamofire的异步请求?我认为该方法在请求完成之前返回播放器对象,或者我错了吗?

提前致谢!

2 个答案:

答案 0 :(得分:0)

这是一个问题,问你基本上是一样的。

AlamoFire GET api request not working as expected

所以基本上发生的事情是你的post请求是在后台队列中调用的。因此,请将其视为致电您的帖子然后继续下一行。因此,由于它在后台线程中,所以在函数返回之前它不会设置变量。

您可以使用完成处理程序,如我提供的链接中详细说明的那样。另一种解决方案是使用NSNotificationCenter。设置观察者,然后在POST请求中发布通知。

所以例如: 首先在类的顶部声明您的通知名称,您将获得发布响应功能。所以其他类可以访问它

let YOUR_NOTIFICATION_NAME = "NOTIFICATION NAME" class YOUR_CLASS{

然后在类中写入POST完成后要执行的代码。

func YOUR_FUNCTION{ ... }

然后在执行POST请求之前,您想添加一个观察者。

NSNotificationCenter.defaultCenter().addObserver(self, selector: "YOUR_FUNCTION", name: YOUR_NOTIFICATION_NAME, object: nil)

然后在POST请求中发布您的通知。

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

答案 1 :(得分:0)

所以我用以下方式构建它:

包含所有请求的Modell类:

let finishedPlayers = "finishedPlayers"
class StrafenkatalogModel: NSObject {
.
.
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?

    //Observer
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "returnPlayers", name: finishedPlayers, object: nil)
    //Request
    Alamofire.request(.POST, "http://smodeonline.com/XXXXXXX.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 teams array
                self.players.append(p)


            }

    }
    return players  
}


func returnPlayers() ->[Player]{
    return self.players
}

然后我想在TableViewController类(Class2)中调用它:

class AddPlayersTableViewController: UITableViewController {

let model:StrafenkatalogModel = StrafenkatalogModel()
var players:[Player] = [Player]()


override func viewDidLoad() {
    super.viewDidLoad()


    // Get Player objects from the model
     NSNotificationCenter.defaultCenter().postNotificationName("finishedPlayers", object: self)
    self.players = self.model.returnPlayers()
    .
    .
    }

但是球员对象是空的。你知道为什么吗?我错了吗?