Search code examples
iosswifttimer

Xcode doesn't Recognise Timer()- Swift 3


New to Swift here- I'm trying to achieve a simple segue operation after predefined times lapses. But for some reason my Xcode isn't recognizing the Timer and gives error "Timer module has no member named scheduledTimer". I couldn't find help anywhere.

CODE:

import UIKit

class ViewController: UIViewController {

    let emptystring = String()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        var time = Timer.scheduledTimer(timeInterval: 8.0, target: self, selector: #selector(changeview), userInfo: nil, repeats: false)
    }

    func changeview (){
        self.performSegueWithIdentifier("GoToMain", sender: self)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "GoToMain"){
            let destination = (segue.destinationViewController as! UINavigationController).viewControllers[0] as! SecondView
            destination.emptyString = emptystring
        }
        print("Segue Performed")
    }

}

Picture also shows my entire code, including the error. NOTE: It's not my own code. I only followed the answer to question in following link:

Xcode Swift 3: Timer and Segue View Controller Error


Solution

  • Timer is a Swift 3 type, but judging from the rest of your method signatures, you appear to be using Swift 2. Use NSTimer in Swift 2.


    Also, for future reference, in addition to the timeInterval typo (which you've now fixed), the third parameter is selector, not selecter.


    So, in Swift 2:

    NSTimer.scheduledTimerWithTimeInterval(8.0, target: self, selector: #selector(changeview), userInfo: nil, repeats: false)
    

    Or in Swift 3:

    Timer.scheduledTimer(timeInterval: 8.0, target: self, selector: #selector(changeview), userInfo: nil, repeats: false)