DaniSmithProductions DaniSmithProductions - 4 months ago 360
Swift Question

presentViewController not working in Swift

Thank you for reading this. I would like to have a functions Swift file where I put all of the functions for my project into, that the other Swift files could call. I am trying to create an alert function in the functions file that, when I pass in a specific string, it shows a specific alert. It was working when it was in the main file, but when I moved it to the functions file, presentViewController is giving me an error, saying "Use of unresolved identifier 'presentViewController'." Please help! Here is my code:
in the functions file:

import Foundation
import UIKit

/**********************************************
Variables
***********************************************/
var canTapButton: Bool = false
var tappedAmount = 0

/**********************************************
Functions
***********************************************/

//the alert to ask the user to assess their speed
func showAlert(alert: String) -> Void
{
if(alert == "pleaseAssessAlert")
{
let pleaseAssessAlert = UIAlertController(title: "Welcome!", message: "If this is your firs time, I encourage you to use the Speed Assessment Tool (located in the menu) to figure which of you fingers is fastest!", preferredStyle: .Alert)
//ok button
let okButtonOnAlertAction = UIAlertAction(title: "Done", style: .Default)
{ (action) -> Void in
//what happens when "ok" is pressed
}
pleaseAssessAlert.addAction(okButtonOnAlertAction)

presentViewController(pleaseAssessAlert, animated: true, completion: nil)
}
else
{
println("Error calling the alert function.")
}
}


Thanks!

Answer

The presentViewController is the instance method of UIViewController class. So you can't access it on your function file like this.

You should change the function like:

func showAlert(alert : String, viewController : UIViewController) -> Void
{
   if(alert == "pleaseAssessAlert")
   {
       let pleaseAssessAlert = UIAlertController(title: "Welcome!", message: "If this is your firs time, I encourage you to use the Speed Assessment Tool (located in the menu) to figure which of you fingers is fastest!", preferredStyle: .Alert)
       //ok button
       let okButtonOnAlertAction = UIAlertAction(title: "Done", style: .Default)
       { (action) -> Void in
            //what happens when "ok" is pressed
       }
       pleaseAssessAlert.addAction(okButtonOnAlertAction)
       viewController.presentViewController(pleaseAssessAlert, animated: true, completion: nil)
   }
   else
   {
       println("Error calling the alert function.")
   }    
}

Here, you are passing a UIViewController instance to this function and calling the presentViewController of that View Controller class.

Comments