2017-04-03 55 views
0

我想在應用程序第一次啓動時運行一段代碼,如果用戶還沒有安裝應用程序。目前,代碼通過另一種方法(清潔)檢查存儲的UserDefaults以查看應用程序是否已安裝。然而,在這種情況下這應該不重要,因爲我硬編碼軟件認爲該應用程序尚未設置。然後我有應用程序檢查,看看它是否已經設置(引用硬代碼)在ViewController的viewDidAppear函數內。在看到它沒有被設置的時候,它會調用一個方法來請求繼續執行SetupViewController。不過出於某種原因,它將兩次調用segue。所以一旦執行了segue並且我看到另一個視圖,它似乎嘗試並再次運行它,然後引發異常。以下是我的代碼和我的日誌輸出。我的代碼中的內容不正確,或者我的代碼邏輯中缺少什麼?我還檢查並確保Segue在Main.storyboard中有適當的標識符。在此先感謝你們!塞格被調用兩次,我不知道爲什麼 - 斯威夫特

ViewDidAppear代碼:

/* 
ViewDidAppear - If the view has appeared after loading we will run some code to check the state of the app. 
*/ 
override func viewDidAppear(_ animated: Bool) { 
    // If the application hasn't been setup and it believes it isn't setup run setup. 
    if(checkIfSetup() != true && hasSetup == false) 
    { 
     print("attempted run") 
     runSetup() 
    } 
     // If the application has been setup and believes it has been setup, load view. 
    else if(checkIfSetup() == true && hasSetup == true) 
    { 
     loadApp() 
    } 
} 

方法要求賽格瑞稱爲 「RunSetup:」

/* 
RunSetup - Runs the setup for the application environment. 
*/ 
func runSetup() 
{ 
    print("Running setup for AppName") // Notify the log that you are running the App's setup. 

    // ## Start by clearing all possibly stored data. ## 

    //REALM - Destroy Database if it exists 

    try! realm.write { 
     realm.deleteAll() 
    } 

    //Begin setting up the environment 
    self.performSegue(withIdentifier: "dismissAndCreate", sender: self) 
    print("tryingSegue") 

} 

日誌輸出:

attempted run Running setup for AppName tryingSegue attempted run Running setup for AppName 2017-04-03 17:12:57.404 AppName[22109:3226052] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Receiver (<AppName.SetupAppViewController: 0x7ffc97824400>) has no segue with identifier 'dismissAndCreate'' *First Throw Stack is then listed*

回答

1

解決方案排在一個非常簡單的方法。我忘了在SetupViewController中創建viewDidAppear或者甚至是viewDidLoad函數。這解決了這個問題。

+1

另外,不要忘記在你覆蓋的方法內部調用超級,例如'super.viewDidAppear(animated)'應該是viewDidAppear()方法中的第一件事,但我沒有在上面的代碼中看到它。根據蘋果的文檔:「如果你重寫這個方法,你必須在你的實現中調用超級。」 –

+0

奇怪的是,當我打電話super.viewDidAppear(動畫)時,它會遇到上一個問題。就好像它將前一個視圖控制器視爲超級視圖控制器一樣。 – surfmaster96