2016-04-08 13 views
0

Bir API ile bağlanmak, bir JSON nesnesini geri almak, bunu bir değişkene atamak ve sonra görüntülemeye çalışmak için Alamofire kullanıyorum. Sorun, değişkenin boş olarak gelmesidir çünkü sunucudan değeri geri almadan önce görüntülemeye çalışmaktadır.Yürütme işlevinden önce Swift'de değişken için nasıl beklenir?

İşte benim Networking.swift dosyasıdır:

class Networking { 

class func postPurchase() { 

    let parameters = [ 
     "login_user": "[email protected]", 
     "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": "[email protected]", "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 
} 

Ve burada değişken olsun ve (PopUpViewControllerSwift kullanarak) göstermek için çalışıyor fonksiyonu var:

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

sayesinde herhangi bir öneri için şimdiden!

+3

Bir tamamlama işleyicisi dahil etmek confirmPurchase değiştirmeniz gerekecektir: Benzer Burada bir şeyler önerdi: http://stackoverflow.com/questions/ 36416163/include-a-dönüş-handler-in-async-arama-swift/36417000? Noredirect = 1 # yorum60583499_36417000 – Shripada

cevap

2

postPurasızlık & confirmPurchas, acsync işlevidir, return kullanmayın. Dene:

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

    let parameters = [ 
     "login_user": "[email protected]", 
     "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": "[email protected]", "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) 
      } 
    } 
} 

ve kullanmak:

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

} 
+0

Başar! Teşekkürler, işe yaradı. Ama bilgiyi yavaşça çekiyor, isteği hızlandırmak için yapabileceğim bir şey var mı? Ayrıca, bu işlem hakkında daha fazla bilgiyi nerede okuyabilirim? Çünkü kod işe yaradı, ama neler olduğunu daha iyi anlamak istiyorum. – Kaidao

İlgili konular