2017-06-23 44 views
1
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    submitTapped() 
    if let scheduleController = segue.destination as? ScheduleController { 
     scheduleController.jsonObject = self.info 
    } 
} 

在submitTapped()中,爲self.info分配了一個值。但是當我運行我的應用程序時,self.info報告爲「無」。我嘗試在三行中的每一行設置斷點,並且似乎submitTapped()在該函數完成之後才執行。迅速控制流程

這是爲什麼?它是否必須處理線程?我怎樣才能得到submitTapped()執行其餘的?我只是試圖從一個視圖控制器移到另一個視圖控制器,同時也將self.info發送到下一個視圖控制器。

UPDATE:

我最後想出來的(大部分),由於低於+我自己的測試答案。

@IBAction func submitTapped() { 
    update() { success in 
     if success { 
      DispatchQueue.main.async { 
       self.performSegue(withIdentifier: "showScheduler", sender: nil) 
      } 
     } 
    } 
} 

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    // I'll probably check the segue identifier here once I have more "actions" implemented 
    let destinationVC = segue.destination as! ScheduleController 
    destinationVC.jsonObject = self.info 
} 

public func update(finished: @escaping (Bool) -> Void) { 
    ... 
    self.info = jsonObject //get the data I need 
    finished(true) 
    ... 
} 
+0

你能展示submitTapped做些什麼,它從哪裏得到它的值? – Scriptable

+0

submitTapped()使用序列化爲JSON的成員變量字符串創建發佈請求,並將其作爲接收JSON的主體,然後將其保存到名爲info([String:AnyObject])的成員變量中。我認爲重要的部分是信息正在被設置在這個函數中,這是與segue相關的唯一部分。你需要我自己發佈代碼嗎? – nuvaryan

+0

@nuvaryan,你可以'執行'繼續什麼時候你會從'json'中得到'閉包'中的值。否則使用'完成'處理程序,如下所示答案 –

回答

1

網絡請求是一個異步任務,發生在後臺,需要一些時間才能完成。您的prepareForSegue方法調用將在數據從網絡返回之前完成。

您應該看看使用completionHandler,並且只有在獲取數據後才觸發segue。

所以你submitTapped功能(可能是最好進行重命名,更新或東西)將會使網絡請求,然後當它獲得的數據傳回將設置self.info屬性,然後調用performSegueWithIdentifier。

func update(completion: (Bool) -> Void) { 
    // setup your network request. 
    // perform network request, then you'll likely parse some JSON 

    // once you get the response and parsed the data call completion 
    completion(true) 
} 

update() { success in 
    // this will run when the network response is received and parsed. 
    if success { 
     self.performSegueWithIdentifier("showSchedular") 
    } 
} 

UPDATE:

瓶蓋,完成處理異步任務是非常困難的,首先要了解。我強烈建議看看這個free course,這是我在Swift中學會如何做的地方,但這需要一些時間。

video tutorial可能會教你基礎知識更快。

+1

爲什麼downvote? – Scriptable

+0

不是我 - 我甚至不能投票。 – nuvaryan

+0

不用擔心,我只是好奇。我想有人沒有讀過你的評論。我遇到過這個問題很多次,特別是當我第一次學習Swift和iOS時。試試看,它應該可以解決你的問題。如果您可以將有關正在發生的事情的信息放入您的問題中,以幫助人們正確理解您的問題,這也會非常有幫助。 – Scriptable