【问题标题】:How to wait for variable in Swift before executing function?如何在执行函数之前等待 Swift 中的变量?
【发布时间】:2016-07-29 04:51:46
【问题描述】:

我正在使用 Alamofire 连接 API,取回 JSON 对象,将其分配给变量,然后尝试显示它。问题是该变量显示为空,因为它试图在从服务器取回值之前显示。

这是我的 Networking.swift 文件:

class Networking {

class func postPurchase() {

    let parameters = [
        "login_user": "admin@poqeta.com",
        "login_password": "p0q3t4",
        "item_id": 5,
        "machine_token": "/HyZyq2FgU4RONnDlzPXWA==",
        "amount": 1
    ]

    Alamofire.request(.POST, "http://poqeta.herokuapp.com/api/v1/purchases/add_item", parameters: parameters, encoding: .JSON)
        .responseData { response in
            print(response.request)
            print(response.response)
            print(response.result)
    }
}

class func confirmPurchase() -> String {
    var token:String = " "

    Alamofire.request(.POST, "http://poqeta.herokuapp.com/api/v1/purchases/purchase", parameters: ["login_user": "admin@poqeta.com", "login_password": "p0q3t4"])
        .responseJSON { response in
            switch response.result {
            case .Success(let data):
                let json = JSON(data)
                let dispenseToken:String = json["token"].stringValue
                print(dispenseToken)
                token = dispenseToken
            case .Failure(let error):
                print("Request failed with error: \(error)")
                return
            }
    }
    return token
}

这是试图获取变量并显示它的函数(使用 PopUpViewControllerSwift):

    @IBAction func showPopUp(sender: AnyObject) {

    var purchase_token:String = " "

    Networking.postPurchase()
    purchase_token = Networking.confirmPurchase()

    let bundle = NSBundle(forClass: PopUpViewControllerSwift.self)
    if (UIDevice.currentDevice().userInterfaceIdiom == .Pad)
    {
        self.popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController_iPad", bundle: bundle)
        self.popViewController.title = "Purchase Complete"
        self.popViewController.showInView(self.view, withImage: nil, withMessage: "Your purchase token is " + purchase_token, animated: true)
    } else
    {
        if UIScreen.mainScreen().bounds.size.width > 320 {
            if UIScreen.mainScreen().scale == 3 {
                self.popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController_iPhone6Plus", bundle: bundle)
                self.popViewController.title = "Purchase Complete"
                self.popViewController.showInView(self.view, withImage: nil, withMessage: "Your purchase token is " + purchase_token, animated: true)
            } else {
                self.popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController_iPhone6", bundle: bundle)
                self.popViewController.title = "Purchase Complete"
                self.popViewController.showInView(self.view, withImage: nil, withMessage: "Your purchase token is " + purchase_token, animated: true)
            }
        } else {
            self.popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController", bundle: bundle)
            self.popViewController.title = "Purchase Complete"
            self.popViewController.showInView(self.view, withImage: nil, withMessage: "Your purchase token is " + purchase_token, animated: true)
        }
    }
}

提前感谢您的任何建议!

【问题讨论】:

标签: ios swift asynchronous alamofire


【解决方案1】:

postPurchase & confirmPurchase 是acsync 函数,不要使用return。 试试:

    class func postPurchase(handleComplete:((isOK:Bool)->())) {

    let parameters = [
        "login_user": "admin@poqeta.com",
        "login_password": "p0q3t4",
        "item_id": 5,
        "machine_token": "/HyZyq2FgU4RONnDlzPXWA==",
        "amount": 1
    ]



     Alamofire.request(.POST, "http://poqeta.herokuapp.com/api/v1/purchases/add_item", parameters: parameters, encoding: .JSON)
            .responseData { response in
                print(response.request)
                print(response.response)
                print(response.result)
                // check request success or failse
//                if  success
                handleComplete(isOK: true)
//                else
//                handleComplete(isOK: false)
        }
    }

class func confirmPurchase(handleComplete:((token:String?)->())){
    var token:String = " "

    Alamofire.request(.POST, "http://poqeta.herokuapp.com/api/v1/purchases/purchase", parameters: ["login_user": "admin@poqeta.com", "login_password": "p0q3t4"])
        .responseJSON { response in
            switch response.result {
            case .Success(let data):
                let json = JSON(data)
                let dispenseToken:String = json["token"].stringValue
                print(dispenseToken)
                token = dispenseToken
                handleComplete(token: token)
            case .Failure(let error):
                print("Request failed with error: \(error)")
                handleComplete(token: nil)
            }
    }
}

并使用它:

 @IBAction func showPopUp(sender: AnyObject) {

    var purchase_token:String = " "

    Networking.postPurchase { (isOK) in
        if isOK{
            Networking.confirmPurchase({ (token) in
                if let tok = token{
                    purchase_token = tok

                    let bundle = NSBundle(forClass: PopUpViewControllerSwift.self)
                    if (UIDevice.currentDevice().userInterfaceIdiom == .Pad)
                    {
                        self.popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController_iPad", bundle: bundle)
                        self.popViewController.title = "Purchase Complete"
                        self.popViewController.showInView(self.view, withImage: nil, withMessage: "Your purchase token is " + purchase_token, animated: true)
                    } else
                    {
                        if UIScreen.mainScreen().bounds.size.width > 320 {
                            if UIScreen.mainScreen().scale == 3 {
                                self.popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController_iPhone6Plus", bundle: bundle)
                                self.popViewController.title = "Purchase Complete"
                                self.popViewController.showInView(self.view, withImage: nil, withMessage: "Your purchase token is " + purchase_token, animated: true)
                            } else {
                                self.popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController_iPhone6", bundle: bundle)
                                self.popViewController.title = "Purchase Complete"
                                self.popViewController.showInView(self.view, withImage: nil, withMessage: "Your purchase token is " + purchase_token, animated: true)
                            }
                        } else {
                            self.popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController", bundle: bundle)
                            self.popViewController.title = "Purchase Complete"
                            self.popViewController.showInView(self.view, withImage: nil, withMessage: "Your purchase token is " + purchase_token, animated: true)
                        }
                    }

                }else{
                    // false --> do st
                }
            })
        } else{
            // do st
        }
    }

}

【讨论】:

  • 太棒了!谢谢,它奏效了。但是它提取信息的速度很慢,我能做些什么来加快请求速度吗?另外,我在哪里可以阅读有关此过程的更多信息?因为代码有效,但我想更好地了解正在发生的事情
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-07
  • 1970-01-01
  • 2019-09-27
  • 1970-01-01
  • 2015-03-01
  • 2012-03-06
相关资源
最近更新 更多