Getting started with iOSUILabelChange Status Bar ColorPassing Data between View ControllersManaging the KeyboardUIButtonUILocalNotificationUIImageViewChecking for Network ConnectivityAccessibilityUITableViewAuto LayoutUIViewUIAlertControllerMKMapViewUIColorNSAttributedStringCAAnimationUITextViewUINavigationControllerConcurrencyCAGradientLayerUIGestureRecognizerCustom UIViews from XIB filesSafari ServicesUIStackViewUIImageUIWebViewCALayeriOS - Implementation of XMPP with Robbie Hanson frameworkSwift and Objective-C interoperabilityNSDateCustom fontsAVSpeechSynthesizerUIBarButtonItemUIScrollViewLocalizationNSNotificationCenterUITextFieldAlamofireUIViewControlleriBeaconCLLocationNSURLSessionUISwitchChecking iOS versionUniversal LinksUICollectionViewPDF Creation in iOSIn-App PurchaseNSTimerCGContext ReferenceUITabBarControllerUISearchControllerUIActivityViewControllerCore LocationFacebookSDKAFNetworkingCTCallCenterUIImagePickerControllerNSUserDefaultsUIControl - Event Handling with BlocksUIBezierPathUIPageViewControllerUIAppearancePush NotificationsKey Value Coding-Key Value ObservationInitialization idiomsStoryboardBackground Modes and EventsFastlaneCAShapeLayerWKWebViewUUID (Universally Unique Identifier)CategoriesHandling URL SchemesRealmARC (Automatic Reference Counting)UIPickerViewDynamic TypeNSURLSWRevealViewControllerSnapshot of UIViewDispatchGroupGCD (Grand Central Dispatch)Size Classes and AdaptivityUIScrollView AutoLayoutIBOutletsAWS SDKDebugging CrashesUISplitViewControllerUISplitViewControllerUIDeviceCloudKitGameplayKitXcode Build & Archive From Command LineXCTest framework - Unit TestingNSDataAVPlayer and AVPlayerViewControllerDeep Linking in iOSApp Transport Security (ATS)Core GraphicsSeguesUIDatePickerNSPredicateEventKitNSBundleSiriKitContacts FrameworkDynamically updating a UIStackViewiOS 10 Speech Recognition APINSURLConnectionStoreKitCode signingCreate .ipa File to upload on appstore with ApplicationloaderResizing UIImageSize Classes and AdaptivityMKDistanceFormatter3D TouchGameCenter LeaderboardsKeychainHandle Multiple Environment using MacroSet View BackgroundBlockContent Hugging/Content Compression in AutolayoutiOS Google Places APINavigation BarUITextField DelegateApp wide operationsUILabel text underliningCut a UIImage into a circleMake selective UIView corners roundedConvert HTML to NSAttributed string and vice verseConvert NSAttributedString to UIImageCoreImage FiltersFace Detection Using CoreImage/OpenCVMPMediaPickerDelegateGraph (Coreplot)NSHTTPCookieStorageFCM Messaging in SwiftCreate a Custom framework in iOSCustom KeyboardAirDropSLComposeViewControllerAirPrint tutorial in iOSUISliderCarthage iOS SetupHealthkitCore SpotLight in iOSUI TestingCore MotionQR Code Scannerplist iOSNSInvocationUIRefreshControl TableViewWCSessionDelegateAppDelegateApp Submission ProcessMVVMUIStoryboardBasic text file I/OiOS TTSMPVolumeViewObjective-C Associated ObjectsPassing Data between View Controllers (with MessageBox-Concept)UIPheonix - easy, flexible, dynamic & highly scalable UI frameworkChain Blocks in a Queue (with MKBlockQueue)SimulatorBackground ModesNSArrayOpenGLUIScrollView with StackView childCache online imagesMVP ArchitectureUIKit DynamicsConfigure Beacons with CoreBluetoothCore DataExtension for rich Push Notification - iOS 10.Profile with InstrumentsApplication rating/review requestMyLayoutUIFontSimulator BuildsSimulating Location Using GPX files iOSCustom methods of selection of UITableViewCellsCustom methods of selection of UITableViewCellsUISegmentedControlSqlCipher integrationCustom UITextFieldSecurityGuideline to choose best iOS Architecture PatternsUIFeedbackGeneratorUIKit Dynamics with UICollectionViewMulticast DelegatesUsing Image AseetsUITableViewCellRuntime in Objective-CModelPresentationStylesCydiaSubstrate tweakCreate a video from imagesCodableFileHandleNSUserActivityRich NotificationsLoad images asyncADDING A SWIFT BRIDGING HEADERCreating an App IDSwift: Changing the rootViewController in AppDelegate to present main or login/onboarding flowattributedText in UILabelUITableViewController

NSTimer

Other topics

Remarks:

An NSTimer allows you to send a message to a target after a specified period of time elapses.

Creating a Timer

This will create a timer to call the doSomething method on self in 5 seconds.

Swift

let timer = NSTimer.scheduledTimerWithTimeInterval(5,
                               target: self,
                             selector: Selector(doSomething()),
                             userInfo: nil,
                              repeats: false)

Swift 3

 let timer = Timer.scheduledTimer(timeInterval: 1,
                                        target: self, 
                                      selector: #selector(doSomething()), 
                                      userInfo: nil, 
                                       repeats: true)

Objective-C

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(doSomething) userInfo:nil repeats:NO];

Setting repeats to false/NO indicates that we want the timer to fire only once. If we set this to true/YES, it would fire every five seconds until manually invalidated.

Manually firing a timer

Swift

timer.fire()

Objective-C

[timer fire];

Calling the fire method causes an NSTimer to perform the task it would have usually performed on a schedule.

In a non-repeating timer, this will automatically invalidate the timer. That is, calling fire before the time interval is up will result in only one invocation.

In a repeating timer, this will simply invoke the action without interrupting the usual schedule.

Invalidating a timer

Swift

timer.invalidate()

Objective-C

[timer invalidate];

This will stop the timer from firing. Must be called from the thread the timer was created in, see Apple's notes:

You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.

Notes: Once timer has been invalidated, its impossible to fire same invalidated timer.Instead you need to initialise the invalidated timer again and trigger fire method.

Timer frequency options

Repeated Timer event

Swift

class ViewController: UIViewController {
 
    var timer = NSTimer()
    
    override func viewDidLoad() {
        NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector(self.timerMethod()), userInfo: nil, repeats: true)
    }

    func timerMethod() {
        print("Timer method called")
    }

    func endTimer() {
        timer.invalidate()
    }
}

Swift 3

class ViewController: UIViewController {
     
        var timer = Timer()
        
        override func viewDidLoad() {
            Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.timerMethod()), userInfo: nil, repeats: true)
        }
    
        func timerMethod() {
            print("Timer method called")
        }

        func endTimer() {
            timer.invalidate()
        }
    }

Must be invalidated manually if desired.

Swift

Non-repeated delayed Timer event

NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: Selector(self.timerMethod()), userInfo: nil, repeats: false)

Swift 3

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

Timer will be fired once, 3 seconds after time of execution. Will be invalidated automatically, once fired.

Passing of data using Timer

If you you want to pass some data with the timer trigger you can do it with the userInfoparameter.

Here is the simple approach that gives brief idea about how you can pass the data to triggered method from the Timer.

[Swift 3]

Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(iGotCall(sender:)), userInfo: ["Name": "i am iOS guy"], repeats:true)

[Objective - C]

NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                      target:self
                                                    selector:@selector(iGotCall:)
                                                    userInfo:@"i am iOS guy" repeats:YES];

The above line of code passing ["Name": "i am iOS guy"] into the userInfo. So now when the iGotCall get call you can get the passed value as below code snippet.

[Swift 3]

func iGotCall(sender: Timer) {
        print((sender.userInfo)!)
    }

[Objective - C]

- (void)iGotCall:(NSTimer*)theTimer {
    NSLog (@"%@", (NSString*)[theTimer userInfo]);
}

Parameters:

ParameterDetails
intervalThe time, in seconds, to wait beforing firing the timer; or, in repeating timers, the time between firings.
targetThe object to call the selector on
selectorIn Swift, a Selector object specifying the method to call on the target
repeatsIf false, fire the timer only once. If true, fire the timer every interval seconds.

Contributors

Topic Id: 2624

Example Ids: 8703,8704,8705,14511,32607

This site is not affiliated with any of the contributors.